Trying to use map function in Threads

If param is a mutable struct (which is seems to be), then it will be shared between all threads, since it is “closed” within the anonymous function definition (x->simulate...). If you are using the same mutable struct between threads, you are likely seeing a race condition.

To make sure each is local, you can use the function deepcopy to create a local copy to use. This is probably the easiest way, but would involve additional copies. Try this:

model, pol_s, pol_n, fix_rates = unzip(ThreadsX.map(x -> simulate_models(deepcopy(param), x),priors));

EDIT: Fixed the order of arguments in simulate_models

If this copying is too much, you can try and make only N copies, where N is the number of threads. This is obviously a more complicated route, but I am happy to explain if this is necessary.

1 Like