Services

Resources

Company

/

Go channels

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)

Fan-in with a Go channel. Three worker goroutines count words in a.txt (120), b.txt (340) and c.txt (95) and send each count into one results channel. The main goroutine receives three times and adds them: 120 + 340 + 95 = 555, with no shared counter and no lock. A red label under the channel warns that a send after close(ch) panics.

Putting this into practice?

Talk to One2N about our backend engineering services

Talk to One2N about our backend engineering services