Is it possible to kill a thread?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: 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?

:bust_in_silhouette: Reply From: Siandfrance

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)

SilvanaBanana | 2020-12-02 11:15