Page 1 of 1

Stop Thread

Posted: Sat Jan 18, 2014 11:20 pm
by IdeasVacuum
We have PlaySound(), and we can stop playback immediately with StopSound(). Am I right to think that the Sound Lib runs in a separate thread?

The reason I ask is that I feel the Thread Library is missing a function: Stop Thread. In some situations, stopping a thread that has a repeat loop is too slow if reliant on checking for a global var change, as recommended in the help. The alternative in that case is Kill Thread, which is too abrupt because the thread cannot run it's clean-up. So, a Stop Thread Function would in an ideal world deliver the best of both - stop quickly but complete it's current cycle.

Am I as mad as the mirror suggests?

Re: Stop Thread

Posted: Sat Jan 18, 2014 11:43 pm
by netmaestro
Sometimes KillThread is fine and you don't need anything else but in other cases where your thread is working with objects like images and gadgets, an abrupt killing of the thread could cause a crash (say a StartDrawing was open and the thread was killed before you got to StopDrawing would be one example). In cases like this, I've had good results with this approach:

Code: Select all

Global tid_1, thread_1_running=0

Procedure Thread_1(void)
  thread_1_running = #True
  While thread_1_running
    ; do stuff
  Wend
EndProcedure

tid_1 = CreateThread(@Thread_1(), 0)
; do stuff
; ...
; User closed the window or something, I want the thread to finish gracefully
thread_1_running = #False
WaitThread(tid_1)
I'm not sure if the compiler could provide a catch-all solution for every case or not, I just don't know. Maybe it's possible.

Re: Stop Thread

Posted: Sun Jan 19, 2014 2:24 am
by IdeasVacuum
Hi Netmaestro

That is the method I normally use, as recommended in the help....... but sometimes it isn't good enough.

Re: Stop Thread

Posted: Tue Jan 28, 2014 11:07 pm
by blueznl
Why do you call it 'too slow' ?

Re: Stop Thread

Posted: Thu Jan 30, 2014 3:25 pm
by IdeasVacuum
...because the global var is changed elsewhere in the app and subject to any kind of potential delay - a delay that probably helped you to decide to create a thread for the most critical part of the process in the first place.