Topic was automatically imported from the old Question2Answer platform.
Asked By
psear
I have a heavy seeking algorithm that will run on 6 threads. When one of them completes the task, they should all be killed to avoid cpu overuse in the background. How can I go about this? I tried:
var t1id = thread1.get_id()
OS.kill(t1id)
but it appears this will kill the whole process. How can I kill just a thread?
It is not safe to stop a thread while he is running, that is why there is no method like Thread::stop.
What you can do is having a boolean that tells the thread if it is terminated. A simple example of it would be:
extends Thread
class_name ThreadWrapper
var terminated: bool = false
func is_terminated() -> bool:
return terminated
#this function will stop the thread
func stop() -> void:
terminated = true
func start(userdata = null, priority: int = Thread.PRIORITY_NORMAL):
.start(self, "do_the_thing", userdata, priority)
func do_the_thing() -> void:
some_loop:
#do something...
if is_terminated():
return #end the function
What if the Thread never terminates? (E.g., has some listener in a while loop)