# Collect data from channels

**URL:** https://discourse.julialang.org/t/collect-data-from-channels/87700
**Category:** General Usage
**Tags:** parallel
**Created:** [September 23, 2022, 1:41pm UTC](https://discourse.julialang.org/t/collect-data-from-channels/87700 "2022-09-23T13:41:02Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![qwerty](https://avatars.discourse-cdn.com/v4/letter/q/4491bb/32.png) [@qwerty](https://discourse.julialang.org/u/qwerty)
#### Post date: [September 23, 2022, 1:41pm UTC](https://discourse.julialang.org/t/collect-data-from-channels/87700/1 "2022-09-23T13:41:02Z")

</div>

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?

```julia
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)

```

---

<div class="post-metadata">

### Author: ![Jeff\_Emanuel](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jeff_emanuel/32/15440_2.png) [@Jeff\_Emanuel](https://discourse.julialang.org/u/Jeff_Emanuel)
#### Post date: [September 23, 2022, 2:31pm UTC](https://discourse.julialang.org/t/collect-data-from-channels/87700/2 "2022-09-23T14:31:02Z")

</div>

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.
