Go by Example

Channel Buffering

Use a fixed-size channel queue to let producers and consumers work at different speeds.

A buffered channel holds a fixed number of values without a receiver ready. A send waits only when the buffer is full, and a receive waits only when it is empty.

The capacity is the second argument to make. These two sends finish before either receive because the channel can hold two values.

package main
 
import "fmt"
 
func main() {
    ch := make(chan string, 2)
    ch <- "first"
    ch <- "second"
    fmt.Println(<-ch)
    fmt.Println(<-ch)
}

In production

Choose capacity from the amount of queued work the system can afford to retain. A buffer can smooth short differences between producer and consumer speed, but it does not make a persistently slow consumer faster. len(ch) is only a momentary observation, so do not use it to coordinate concurrent work.

Enjoyed this? Get more software craft delivered to your inbox.