Home > OS >  Julia Multithreading: how to control local scope of variables
Julia Multithreading: how to control local scope of variables

Time:01-05

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:

  • Is there a way to define wether the array should be shared or each threads has its how copy. For example the way it work in OpenMP with private or shared declaration system for variables?
  • Initializing the array in the loop is not an option as it will create reallocate memory at each step instead of once for each threads.
  • Is there a different julia library that is better suited for this kind of application?
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)

CodePudding user response:

a pattern for a thread-local buffer is this:

function calcparallel(buf::AbstractArray,result::AbstractArray)
   bufs = [zeros(3) for _ in Threads.nthreads()]
   @threads 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

  •  Tags:  
  • Related