Calling another function in loop using Base.Threads

Dear All,

I am having a problem running the following code in parallel. Please suggest how to achieve the parallelization to populate an array by a so-called very computationally expensive function.

Thanks and Regards


using Base.Threads
using LinearAlgebra,NumericalIntegration

x = collect(0:1e-6:1);

function test_func(a)
  return a*a;

test = zeros(length(x));

Threads.@threads for i = 0:length(x)
	 test[i] = test_func(x[i]);

println("integrate  = ", integrate(x,test) );
println(" ");

what problem?

this is gonna be slow, you’re running code in global with non-constant global variable

ERROR: LoadError: TaskFailedException
 [1] wait
   @ ./task.jl:334 [inlined]
 [2] threading_run(func::Function)
   @ Base.Threads ./threadingconstructs.jl:38
 [3] top-level scope
   @ ./threadingconstructs.jl:97

    nested task error: BoundsError: attempt to access 1000001-element Vector{Float64} at index [0]
     [1] getindex(A::Vector{Float64}, i1::Int64)
       @ Base ./array.jl:861
     [2] macro expansion
       @ ~/TestProg/threads.jl:15 [inlined]
     [3] (::var"#2#threadsfor_fun#1"{UnitRange{Int64}})(onethread::Bool)
       @ Main ./threadingconstructs.jl:85
     [4] (::var"#2#threadsfor_fun#1"{UnitRange{Int64}})()
       @ Main ./threadingconstructs.jl:52
in expression starting at /home/amol/TestProg/threads.jl:14

Julia Arrays have one-based indexing, and use inclusive ranges.

Use 1:length(x) or, preferably, eachindex(x)

I am new to these ‘Threads’. How to exactly achieve the same using Base.Threads package? I would be really grateful for your help in this regard.

Thanks! Gotcha…solved it. :smiley:

But also make sure to put your code in functions, otherwise, threads will be slow.