multithreadingjulia

How to multithread creation of Array Julia


I have some list of parameters and some complicated function that computes something based on these parameters. I then want to compute some list in the following way:

params = [1,2,3]
func(x) = x+1

myList = [ func(x) for x in params]


How can I apply multithreading to generate myList? I thought something like the following would work

myList = [func(x) @bthreads for x in params]

but it does not.

In my actual case, func(x) is a function that generates some matrix and returns its eigenvector with smallest eigenvalue. Does it even make sense to use threading on something like this? (The matrices are say 50x50, and I do this computation around 50x50 times)


Solution

  • You can use Threads.@spawn inside a list comprehension to build the results asynchronously:

    func(x) = x * x
    params = [1, 2, 3]
    
    list = fetch.([Threads.@spawn func(x) for x in params])
    
    @show list
    # list = [1, 4, 9]
    

    The list comprehension builds a list of tasks. Then, fetch waits for each task to finish and returns a list of results.