Goroutines and Channels

A goroutine is a task running alongside others. A channel is a pipe they use to pass values.

The idea

A goroutine is like an extra worker in a kitchen: go f() says “you, start doing f, I will carry on”. Workers should not reach into each other’s pockets; they hand things over a channel, like a slot in the kitchen wall.

An unbuffered channel has no shelf: the cook and the waiter must meet at the slot at the same moment, so whoever arrives first waits (blocks). A buffered channel has a shelf with room for N plates: the sender only waits when the shelf is full, the receiver only when it is empty. close(ch) tells the receivers “no more plates are coming”.

Note: real Go chooses the order in which goroutines run. These animations show one possible schedule.

Watch it work

Try it

Common mistakes