Tasks and threads
Posted: Tue May 03, 2011 7:46 pm
Do you guys think following code can be optimised. It looks ok, but perhaps there are better ways to spread tasks evenly over different threads. I want to implement multi-core support in a real-time audio application.
(surely the delay()'s and so on are only for demonstrational purposes
)
(surely the delay()'s and so on are only for demonstrational purposes

Code: Select all
#NrOfThreads=3
#NrOfTasks=50
Structure MyThread
ThreadId.l
MutexId.l
SemaphoreId.l
EndStructure
Global Dim arrThreads.MyThread(#NrOfThreads-1)
OpenConsole()
Procedure MyThread(i)
Repeat
PrintN(" -Waiting Thread->" + Str(i))
WaitSemaphore(arrThreads(i)\SemaphoreId)
LockMutex(arrThreads(i)\MutexId)
PrintN(" -Running Thread->"+str(i))
For j=1 to 10
delay(50)
Next
UnlockMutex(arrThreads(i)\Mutexid)
ForEver
EndProcedure
For i = 0 to #NrOfThreads-1
arrThreads(i)\SemaphoreId=CreateSemaphore()
arrThreads(i)\MutexId=CreateMutex()
arrThreads(i)\ThreadId=CreateThread(@MyThread(),i)
Next
PrintN("Waiting in Main")
NrOfTasks=#NrOfTasks
delay(500)
Repeat
For i= 0 to #NrOfThreads-1
if NrOfTasks
if TryLockMutex(arrThreads(i)\MutexId)
PrintN("Remaining tasks->"+str(NrOfTasks))
NrOfTasks-1
UnlockMutex(arrThreads(i)\MutexId)
PrintN(" -Signalling Thread->"+str(i) )
SignalSemaphore(arrThreads(i)\SemaphoreId)
delay(10)
EndIf
EndIf
Next
Until NrOfTasks=0
Printn("All tasks ended, press any key to close")
Repeat
delay(10)
until Inkey()