liveBook · Manning

Channel capacity

As explained in 100 Go Mistakes and How to Avoid Them

Channel capacity is the number of values a buffered Go channel can hold before a send blocks.

Channel capacity is the number of values a buffered Go channel can hold before a send blocks. An unbuffered channel has capacity zero; a buffered channel has capacity of at least one. section 9.7

The second send blocks

With capacity one, the first send succeeds immediately. After the channel is full, the second send blocks until a receiver removes a value. section 9.7

Choose the channel form according to the coordination required:

  • Use an unbuffered channel when the send and receive must synchronize. section 9.7
  • Use a buffered channel when a sender may continue while capacity remains, remembering that buffering provides communication but not strong synchronization. section 9.7
ch1 := make(chan int)
ch2 := make(chan int, 0)

Compare the equivalent zero-capacity declarations for an unbuffered channel. section 9.7

ch3 := make(chan int, 1)
ch3 <-1                   #1
ch3 <-2                   #2

Trace how capacity one permits the first send and blocks the second. section 9.7

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Explains zero and positive capacities, send blocking, and synchronization consequences without developing sizing heuristics.
Examples
Uses zero-capacity declarations and a capacity-one channel whose second send blocks.
What it assumes
Assumes goroutines and channel send/receive operations while establishing buffered and unbuffered behavior directly.
What you can do after
Evaluate/understand whether a channel send proceeds immediately or blocks, and whether the channel provides synchronization.
How it connects
Connects channel capacity with buffered channels, unbuffered channels, goroutines, communication, and synchronization.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.