I woud like to simultaneously use a Channel to produce values at which a function must be evaluated, and parallelise the evaluation of this function using Threads.@threads.
In the absence of any multi-threading, my MWE is:
#####
# Produces input values
function producer(c::Channel)
nb_inputs = rand(1:10)
for n=1:nb_inputs
println("Generating | ",n)
put!(c,n)
end
end
#####
# Expensive function
function f(n::Int64)
println("Running | ",n)
sleep(2.0)
end
#####
# Evaluates the function over all the input values
function test()
for n in Channel(producer)
f(n)
end
end
#####
test()
Here, producer(c) returns input values; f(n) is an expensive function (whose evaluations are all independent from one another); and test() evaluates the function over all the input values returned by the producer.
Now, I would like to run the for loop in test() in parallel over multiple threads.
Naively, I tried
Threads.@threads for n in Channel(producer)
Yet, this fails because the number of elements of the Channel is initially unknown.
How could I circumvent this issue?