liveBook · Manning

Done channel pattern

As explained in Go in Practice, Second Edition

The done channel pattern uses a channel to signal cancellation or completion so concurrent operations can stop and perform cleanup.

A done channel coordinates clean shutdown between goroutines. The receiving goroutine signals completion, while the sending goroutine stops work, closes the message channel, and returns. section 5.3.2

Use the pattern to avoid common channel-lifecycle failures:

  • Let the sender close the message channel; closing it from a receiver while a send is active causes a panic. section 5.3.2
  • Do not treat a closed channel's zero value as an ordinary message; receive its status when distinguishing closure matters. section 5.3.2
  • Give the sender a dedicated done channel and select on it so cancellation can trigger cleanup before return. section 5.3.2

Timed producer shutdown

A main goroutine reads messages until a timeout, sends a completion signal on done, and returns. The producer selects on done, logs completion, closes its output channel, and exits; otherwise it sends another message and waits briefly.

How Go in Practice, Second Edition covers it

How deep it goes
Demonstrates unsafe closure, zero-value receives, and a complete done-channel implementation with timeout-driven cleanup.
Examples
Uses a timed message producer, an unsafe receiver close, and a sender-side cleanup implementation.
What it assumes
Assumes goroutines, channel communication, select, and basic channel closure while clarifying closure ownership and zero-value receives.
What you can do after
Build it from scratch with Go channels and select to stop a sender and close its output without a send-on-closed-channel panic.
How it connects
Connects goroutines, channels, select, channel closing, timeouts, and directional channel parameters.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Practice, Second Edition. The section links point to the parts of the book it draws on.