The Godot Q&A is currently undergoing maintenance!

Your ability to ask and answer questions is temporarily disabled. You can browse existing threads in read-only mode.

We are working on bringing this community platform back to its full functionality, stay tuned for updates. | Twitter

+4 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()

but it appears this will kill the whole process. How can I kill just a thread?

in Engine by (276 points)

1 Answer

+2 votes

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:
        #do something...
        if is_terminated():
            return #end the function
by (43 points)
edited by

What if the Thread never terminates? (E.g., has some listener in a while loop)

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 Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.