Multithreading and rand within a specific range

Hello,

I am trying to find parameters that make my model work using brute force. To do this I need to run my model many times varying the parameters each time. It works when I do it without multithreading but I want to run many more trials.

I’ve been reading the Parallel Computing doc as well as these forums so I know I need to have an individual rand for each thread but I am not sure how to do this. Julia is my first computing language and (I think) I have a basic understanding of programming.

 using Random; import Future 

function parameter_search2()
    for i in 1:1000000
    # Threads.@threads for i in 1:1000000       # this one
    # @threads for i in 1:1000000               # or this one?
        
        bioS = sol[end] # this is generated once, outside of this function
        target_species = 42
       
        catch_max2 = rand(Uniform(0,1)) # should it be rand([threadid()Uniform(0,1)]) ?
        scaling2 = rand(Uniform(0,1))
        maintenance2 = rand(Uniform(0,0.5))
        P_catch2 = rand(Uniform(0,0.5))
        μ2 = rand(Uniform(0,0.5))

        # after this point I run a differential equation using these random value inputs;
        # and then println when a criteria is reached
end

Any advice or example is appreciated.

Threads.@threads should work. You would also have to store the parameters that are successful in a threadsafe way, see e.g., a ReentrantLock

1 Like

This is actually no longer true. The global RNG is now thread safe, the docs are just not updated (https://github.com/JuliaLang/julia/pull/33419).

1 Like

Thank you for your quick replies!

@baggepinnen Are you referring to something like this ?

@kristoffer.carlsson Does this mean I can include Threads.@threads for i in 1:1000000 and leave it written as catch_max2 = rand(Uniform(0,1)) ?

It depends a bit on how Distributions has implemented rand on their types but as long as they just use the global random number generator from Julia, it should be fine,.

Thanks!