Hi,
(This maybe should be in the Julia newbies category?)
I know from documentation that if you bind a channel to multiple tasks,
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:
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