how to kill threads safely

Just starting out? Need help? Post your questions and find answers here.
nsstudios
Enthusiast
Enthusiast
Posts: 275
Joined: Wed Aug 28, 2019 1:01 pm
Location: Serbia
Contact:

how to kill threads safely

Post by nsstudios »

Hi all,

I'm wondering if there is a way to kill a thread safely without relying on a global variable, or any manual check, for that matter.
The code I have uses multiple loops, so I would have to place the manual check for the kill in all of them, so I'm wondering if there's an easier way to signal a thread to close?
I'm looking for a cross-platform solution if possible.

Thanks.
infratec
Always Here
Always Here
Posts: 6883
Joined: Sun Sep 07, 2008 12:45 pm
Location: Germany

Re: how to kill threads safely

Post by infratec »

Code: Select all

Structure ThreadParameterStructure
  Thread.i
  Mutex.i
  Semaphore.i
  Exit.i
EndStructure


Procedure ThreadProcedure(*Parameter. ThreadParameterStructure)
  
  Repeat
    Delay(500)
    Debug "Running"
  Until *Parameter\Exit
  
  Debug "Termminated"
  
EndProcedure



Define ThreadParameter.ThreadParameterStructure


ThreadParameter\Thread = CreateThread(@ThreadProcedure(), @ThreadParameter)
If ThreadParameter\Thread
  
  Delay(3000)
  
  ThreadParameter\Exit = #True
  
  If WaitThread(ThreadParameter\Thread, 1000) = 0
    Debug "Should never be reached"
    KillThread(ThreadParameter\Thread)
  EndIf
  
EndIf
nsstudios
Enthusiast
Enthusiast
Posts: 275
Joined: Wed Aug 28, 2019 1:01 pm
Location: Serbia
Contact:

Re: how to kill threads safely

Post by nsstudios »

Thanks, but this is exactly what I don't want, because I have multiple other loops inside the thread, and just surrounding them with a repeat/while with the manual check wouldn't work because they might take a while to complete, forcing me to add the check to all of them, and even that wouldn't work for cases where you have a blocking function. Imagine I want to exit but the thread is currently frozen because of, e.g., an alternative to delay(20000). That means if I press escape to trigger the termination of a thread, I'd have to wait up to 20 seconds for it to close, or force it to be killed with killThread, which is exactly what I'm trying to avoid so I don't end up running into problems.
So, what I'm asking for is: imagine you had a thread that contained a blocking function that you couldn't inject the termination checks in to. How would you close such a thread without calling killThread?
Post Reply