+2 votes

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?

asked Jul 9 in Engine by psear (103 points)

1 Answer

+1 vote

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
answered Jul 16 by Siandfrance (39 points)
edited Jul 16 by Siandfrance
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.