Using @threads in [f(x) for x in 1:max_X]

This is a dumb example, but I would like to learn a bit more about its syntax. I was expecting that adding @threads right in front of “for” would work out to make an array.

[f(x) @threads for x in 1:max_X]
[@threads f(x) for x in 1:max_X]

However, none of them works.

As far as I know, you can’t use Threads.@threads with a comprehension.

You can though use a threaded map. For example,

using Distributed
pmap(f, x)

and it’ll apply f to each element of x in a parallel way.

Alternatively, you can use the map from the package ThreadsX.

1 Like

Note that while parallel this is not multithreaded. Instead it uses multiple worker processes (which btw need to be started first).


fetch.([Threads.@spawn f(i) for i in x]) usually does the trick for me. I don’t know if it will be the most performant but it’s good enough if i quickly want to parallelize something


There is also

1 Like

Thank you very much, everyone.
I’ve decided to stick with multithreading due to the cluster system.
ThreadsX seems very impressive!