Services

Resources

Company

Go channels

A channel is a typed pipe between goroutines. One goroutine sends a value with ch <- v and another receives it with v := <-ch. Because the send and the receive synchronize, a channel moves data and coordinates timing in one step, without a separate lock.

How it works

make(chan int) creates an unbuffered channel: a send blocks until a receiver takes the value. make(chan int, 3) creates a buffered channel that holds up to 3 values, so senders block only when the buffer is full. The sender calls close(ch) when it has nothing more to send, and for v := range ch keeps receiving until the channel is closed and empty.

For example, a fan-in word count starts 3 worker goroutines, one per file, and each sends its count on one shared results channel. The main goroutine receives 3 times: 120 from a.txt, 340 from b.txt and 95 from c.txt, and prints the total, 555. No worker touches a shared counter, so there is nothing to lock.

Why it matters in production

Channel bugs are usually about who waits for whom. If every goroutine is blocked, Go stops with fatal error: all goroutines are asleep - deadlock!; if only some are, they leak quietly. Sending on a closed channel panics, so only the sender closes, and with many senders you close after a sync.WaitGroup finishes. A buffered channel also gives you backpressure: when consumers fall behind, the full buffer slows producers down.

See also

On the One2N blog

References

  1. Channels (Effective Go)

  2. Channel types (The Go programming language specification)

Four-panel comic about Go channels: three workers count words in three files and Asha needs one total without a shared counter; a channel is a typed pipe where an unbuffered send waits for a receiver and a buffered one waits only when full; 120 plus 340 plus 95 arrive on one channel and main sums 555; Asha closes channels from the sender and ranges over them.