JULIA / CHAPTER 13
Tasks, channels, and producer lifecycles
AdvancedCoordinate values and completion between asynchronous tasks.
By the end of this chapter
- Use a typed channel as a producer-consumer boundary
- Explain blocking and channel closure
- Distinguish cooperative tasks from automatic CPU parallelism
The idea
Tasks allow computations to pause and resume while waiting for other work. A Channel carries values between producers and consumers with explicit capacity and element type. A producer can wait when the channel has no room, and a consumer can wait when no value is available. A zero-capacity channel synchronizes a handoff rather than storing a backlog.
The Channel constructor that runs a producer function binds its lifetime to that task and closes the channel when the task terminates. Iterating the channel consumes values until closure and exhaustion, so completion is part of the protocol. A task is not by itself a promise of simultaneous execution on multiple CPU cores. Use deliberate threading mechanisms where appropriate, and still account for shared state, failure propagation, and shutdown.
ch = Channel{Int}(0) do output
for n in 1:3
put!(output, 2 * n)
end
end
println(sum(ch))12
The producer sends 2, 4, and 6; its bound task then terminates, closes the channel, and lets the consumer finish.
Try it yourself
Design a bounded producer-consumer pipeline and document who closes the channel on success and failure.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING