Collect data from channels

I use a Pkg that uses threads and allows you to pass a function that does something at each iteration.
I want to send strings to a Channel and put them in a vector. Is this code the best way to do this? Or are there simpler and more elegant ways?

elements = String[]
c = Channel{Union{String, Nothing}}(200)

t = @task while true # collect strings from threads
    el = take!(c)
    if el === nothing # if get nothing stop task
        break
    else
        push!(elements, el)
    end
end

schedule(t)  # start collecting

Threads.@threads for i ∈ 1:100 # example parallel computation
    put!(c, "hello, $i")  # In real cases I encapsulate this in the function to pass
end

put!(c, nothing)  # stop collecting
wait(t)  
close(c) # close Channel

println(elements)

I would skip the Union with Nothing and put!(c, nothing) and make the task catch the exception that occurs when taking from a closed channel. Also, put the task code in a function so you don’t access global variables.

1 Like