When the respective thread is finished, the global variables changed in the thread should be processed in the main routine (e.g. window events).
I'm currently testing with "SignalSemaphore" and "PostEvent". Depending on the elapsed time of the thread, the global variable "string" is overwritten by the 2nd thread and the first value is lost. Here's a small example:
Code: Select all
EnableExplicit
Enumeration FormGadget
#wnd
#Btn_thread
EndEnumeration
Enumeration #PB_Event_FirstCustomValue
#EventThreadBegins
#EventThreadEnds
EndEnumeration
Global Mutex = CreateMutex()
Global Semaphore = CreateSemaphore()
Global string.s = ""
Define event, thread1, thread2, thread3
Procedure ThreadProcedure(*value)
Protected a,b
LockMutex(Mutex)
; do something
For a = 1 To 2
For b = 1 To 5
Debug "Thread "+Str(*value)+" Line "+Str(b)
Delay(1) ; ****** test with diff values (1,10,50)
Next b
Next a
; var to be changed and used again in main program
string = "MyThread "+Str(*value)
UnlockMutex(Mutex)
; signal/event processing finished
SignalSemaphore(Semaphore)
PostEvent(#EventThreadEnds)
EndProcedure
; -------
OpenWindow(#wnd,50,50,200,150, "Thread", #PB_Window_SystemMenu)
ButtonGadget(#Btn_thread,25,50,120,25, "start threads")
Repeat
event = WaitWindowEvent(25)
Select event
Case #EventThreadBegins
Debug "#EventThreadBegins : "+ string
Case #EventThreadEnds
Debug "#EventThreadEnds : " + string
Case 0
If TrySemaphore(Semaphore)
Debug "Semaphore : " + string
EndIf
Case #PB_Event_Gadget
Select EventGadget()
Case #Btn_thread
ClearDebugOutput()
; ------- Start Threads (later in loop)
thread1 = CreateThread(@ThreadProcedure(), 1)
Delay(25) ;Delay To ensure threads running sequentially
thread2 = CreateThread(@ThreadProcedure(), 2)
Delay(25)
thread3 = CreateThread(@ThreadProcedure(), 3)
EndSelect
EndSelect
Until event = #PB_Event_CloseWindow
FreeMutex(Mutex)
FreeSemaphore(Semaphore)
What do I have to do to ensure that the variables of the first thread can be processed first by e.g a "PostEvent" and are not immediately overwritten by the second thread? Mutex alone doesn't seem to be enough here... At this point, thread 2 should wait until it is released. I don't want to use "WaitThread" at this point because I don't want the program to stop.
Thx in advance!
.



