Take the value from the first thread which returns?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By psear

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?

:bust_in_silhouette: Reply From: cgeadas

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.