+1 vote

I have a reasonably heavy algorithm which returns a variable. To speed things up, I want to run it on multiple threads. it typically takes from 3-10 seconds, so what I am aiming for is to start 4 threads, for example, and then take the value from the first one that returns. There is a lot of randomisation in the algorithm, hence the variation in the time it takes to produce the variable. Something like this:

var thread1 = Thread.new()
var thread2 = Thread.new()

func algorithm():
    [heavy algorithm]
    return product

func generate_product():
    thread1.start(self, "algorithm")
    thread2.start(self, "algorithm")
    [somehow take the value from the first thread which returns]
    return product

the problem is, if I have something like:

product1 = thread1.wait_to_finish()
product2 = thread1.wait_to_finish()

it will wait until all the threads have finished, how do I go about this?

in Engine by (276 points)

1 Answer

0 votes

I don't know if it's the best way, but you can pass the value from function to function.

In order to have threads working you need 3 functions: a main function that starts the thread; a function that is the thread; and a function that takes the result of the thread and processes it.

func main():
    # Creates and calls the thread

     var thr = Thread.new()
     thr.start(self, "algorithm", thr)

func algorithm(thr):
    # Take the thread reference as an argument
    # Do the heavy processing
    var product = [heavy algorithm]
    call_deferred("post_processing", thr)
    return product

func post_processing(thr):
    # Receives the thread reference as an argument
    var product = thr.wait_to_finish()
    [do stuff with product]

With this you can always keep the reference of the thread and, when you want more than one thread, you can build an array (almost a queue) with these references and then, in the post_processing method, decide how to deal with the output of each individual thread, but use the same code for all the threads you create.

Again, I don't know if this is the best way to do threads, I've learn about them today, but I have this working for me.

by (111 points)
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.