Hi,
I'm trying to use threads to perform some intensive processing in the background of a program, dependant on the position of a slider gadget, while the slider gadget is being dragged around. Here's a program that demonstrates the kind of problems I'm having:
Code: Select all
Global CS.CRITICAL_SECTION
Global CSInitialized.l
Global value, ThreadRunning
Procedure Thread(Parameter)
If CSInitialized = #False
InitializeCriticalSection_(CS)
CSInitialized = #True
EndIf
Debug "Thread started"
Repeat
EnterCriticalSection_(CS)
tempvalue = value
LeaveCriticalSection_(CS)
change = #False
For a = 1 To 50
; Processor-intensive delay loop: (causes crashes!)
;For b=1 To 50000
; b+1
; b-1
;Next
; Delay statement:
Delay(50)
; If slider has moved, exit and restart the loop
EnterCriticalSection_(CS)
If value <> tempvalue
LeaveCriticalSection_(CS)
Debug "Value changed: " + Str(value)
change = #True
Break
Else
LeaveCriticalSection_(CS)
EndIf
Debug a
Next
Until change = #False
Debug "Thread Finished"
ThreadRunning = #False
EndProcedure
OpenWindow(0, 300, 400, 300, 120, "Threads demo", #PB_Window_SystemMenu)
TrackBarGadget(0,20, 40, 256, 40, 0, 255)
CreateImage(0, 300, 300)
Repeat
EventID = WaitWindowEvent()
If EventID = #PB_Event_Gadget And EventGadget() = 0
value = GetGadgetState(0)
If ThreadRunning = #False
ThreadRunning = #True
Debug "Creating thread"
CreateThread(@Thread(), 0)
EndIf
EndIf
Until EventID = #PB_Event_CloseWindow
I tried to implement the Critical Section commands as described in this post: viewtopic.php?t=11975.
I've figured out the crashes seem to be caused by accessing global variables, so I've tried protecting the commands involving 'value' with the Enter and Leave critical section commands. I've also tried putting the commands in different places but they don't appear to have any effect.
Can anyone help?
Thanks,
Paul