Julia Channels
Channels are queues that pass values between tasks. A bounded channel holds only a fixed number of values at a time.
One value passes through a channel
A value is put into the channel. Taking it gives the same value back.
channel = Channel{Int}(2)
put!(channel, 7)
println(take!(channel))A producer fills a channel while a consumer takes values
A task puts three values into the channel. The main work takes them in order.
channel = Channel{Int}(2)
producer = @async begin
for v in [10, 20, 30]
put!(channel, v)
end
close(channel)
end
println(take!(channel))
println(take!(channel))
println(take!(channel))Taken values add to one total
A task puts three values into the channel. The main work takes all three and adds them.
channel = Channel{Int}(2)
producer = @async begin
for v in [5, 15, 25]
put!(channel, v)
end
close(channel)
end
first_value = take!(channel)
second_value = take!(channel)
third_value = take!(channel)
println(first_value + second_value + third_value)Example
channel = Channel{Int}(2)
producer = @async begin
for v in [1, 4, 9, 16]
put!(channel, v)
end
close(channel)
end
for i in 1:4
println(take!(channel))
endKey points
- Channel: a queue that passes values from a producer to a consumer.
- Use Channel{Int}(2) to make a queue that holds at most two integers.
- Use put! to add a value to a channel.
- Use take! to remove the next value from a channel.
- Use close to mark a channel as finished after the last value.
In this example, a task puts four values into a bounded channel, the main work takes them one at a time in order, and the channel closes after the last value.
Note
A producer waits when a full channel has no free space, until the consumer takes a value.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
A channel holds at most two values and is full. What does a producer do when it tries to put a third value?