# Close Channels when the Last Task Finishes

**URL:** <https://discourse.julialang.org/t/close-channels-when-the-last-task-finishes/82943>\
**Category:** General Usage\
**Tags:** multithreading\
**Created:** [June 17, 2022, 9:12pm UTC](https://discourse.julialang.org/t/close-channels-when-the-last-task-finishes/82943 "2022-06-17T21:12:37Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![juliafriend](https://avatars.discourse-cdn.com/v4/letter/j/2acd7d/32.png) [@juliafriend](https://discourse.julialang.org/u/juliafriend)\
**Post date:** [June 17, 2022, 9:12pm UTC](https://discourse.julialang.org/t/close-channels-when-the-last-task-finishes/82943/1 "2022-06-17T21:12:37Z")

</div>

Hi,  
(This maybe should be in the Julia newbies category?)  
I know from documentation that if you bind a channel to multiple tasks,

```julia
bind(c, t1) 
bind(c, t2) 

```

the channel will close when any one of the tasks finishes and returns.

What this means is that if `t1` and `t2` are both putting elements into the channel and `t1` finishes, `t2` will be blocked indefinitely (or more realistically, if you’re using `errormonitor(t2)`, throw an error).

What if I wanted to have a channel with multiple tasks writing to it and only terminate when all those tasks finished?  
The most elegant solution I have at the moment is to make another task from the main thread (so it can access the handlers of the other threads) that waits for them to finish. Then bind this new function to the channel.

_ **Here’s an example I wrote you can copy and paste:** _

```julia

c = Channel(30)

task_handler_1 = @async begin
    sleep(3)
    for i in 1:10
        put!(c, 1)
    end
end

task_handler_2 = @async begin
    sleep(10)
    for i in 1:10
        put!(c, 2)
    end
end

errormonitor(task_handler_1)
errormonitor(task_handler_2)

my_task_handler_array = [task_handler_1, task_handler_2]
wait_for_tasks_to_finish = @async begin
    for task in my_task_handler_array
        wait(task)
    end
end

bind(c, wait_for_tasks_to_finish)

for i in c
    @show i
end

```

_ **Is there a more elegant solution that doesn’t require this `wait_for_tasks_to_finish`** _
