stefanJonB
stefanJonB

Reputation: 60

Julia Multithreading: how to control local scope of variables

I am fairly new to julia and I am trying to use the multithreading capacities of julia.

Below is a toy example that I made to explore julia capacities. It is a very simplified version of what I am trying to do. I need to parallelize the loop. Inside this loop I am performing some calculations that require a buffer array (in the example below the buffer is of course unecessary). also the buffer cannot be shared between threads as it would lead to a race condition.

I am using the macro @threads to parallelize my loop. The problem is that i cannot find a way to define how the different threads should interact with the buf array:

function calcparallel(buf::AbstractArray,result::AbstractArray)

   @threads for i=1:length(result) 
        buf[1] = float(i)         
        buf[2] = 1.0/float(i) 
        buf[3] = sqrt(i)

        result[i] = buf[1] * buf[3] + buf[2]

    end
    return result 
end

n = 1000
nn = 10
buf2 = zeros(Float64,nn)
result2  = zeros(Float64,n)


@time calcparallel(buf2,result2)

Upvotes: 2

Views: 770

Answers (1)

jling
jling

Reputation: 2301

MUST READ: https://julialang.org/blog/2023/07/PSA-dont-use-threadid/

You need :static since Julia 1.8 because that was when default changed to :dynamic, but read the official PSA blog post above for a better pattern.

a pattern for a thread-local buffer is this:

function calcparallel(buf::AbstractArray,result::AbstractArray)
   bufs = [zeros(3) for _ in Threads.nthreads()]
   @threads :static for i=1:length(result) 
        buf = bufs[Threads.threadid()]
        buf[1] = float(i)         
        buf[2] = 1.0/float(i) 
        buf[3] = sqrt(i)

        result[i] = buf[1] * buf[3] + buf[2]

    end
    return result 
end

Upvotes: 6

Related Questions