Go Channels — Go

Railway watchtower: 20 levels predicting the output of goroutines, channels, select, WaitGroup, Mutex and context. A deterministic, seeded CSP scheduler.

What you learn in this game

A goroutine is a function running alongside the others. The word go before a call starts one, and the next line runs straight away without waiting. The program stops as soon as main returns. Goroutines that are not done are not waited for.

sync.WaitGroup counts work that is not finished. wg.Add(n) raises the count before the goroutines start, each goroutine calls wg.Done() when it is done (usually with defer), and wg.Wait() waits until the count is zero. Every Done happens before Wait returns: whatever a goroutine did before Done has surely happened when main goes on.

A channel is a gutter between goroutines. ch <- v sends, v := <-ch receives. A channel from make(chan T) has no buffer: sender and receiver must meet. A rule of the Go memory model: a send happens before its matching receive completes. Whatever the sender wrote before sending is seen by the receiver after receiving.

A channel parameter can carry a direction. in <-chan int means the function may only receive from in; out chan<- int means it may only send. The direction is checked at build time. A program that sends on a receive-only channel never runs.

make(chan T, n) makes a channel with a buffer of n. A send finishes at once while the buffer is not full; a receive finishes at once while it is not empty. Values leave in the order they came in. Buffer full and nobody receiving: the sender waits.

close(ch) marks that no more sends will come. Values still in the buffer can be received. Once it is empty, a receive returns at once with the zero value and ok == false. for v := range ch stops exactly then. The sender is the one who closes; sending on a closed channel panics.