liveBook · Manning

Channel

As explained in 100 Go Mistakes and How to Avoid Them

A channel is a Go synchronization and communication mechanism through which goroutines send and receive typed values.

A channel connects goroutines so they can communicate by sending and receiving typed values. The mistake is to treat every channel as providing the same synchronization: buffering changes when a sender can proceed. section 8.3 section 9.7

Choose the channel type for the coordination required:

  • An unbuffered channel has zero capacity. A send blocks until a receiver is ready, synchronizing the sending and receiving goroutines. section 8.3 section 9.7
  • A buffered channel accepts sends until its capacity is full; the next send blocks until a receiver makes room. A successful send alone does not mean the receiver has reached the corresponding receive. section 9.7
ch3 := make(chan int, 1)
ch3 <-1                   #1
ch3 <-2                   #2

With capacity one and no receiver, the first send proceeds; the second blocks. section 9.7

Channels and mutexes are complementary. Use channels to communicate results or coordinate stages; a mutex is generally better for protecting a shared resource accessed by parallel goroutines. Do not force channels into every concurrency problem. section 8.3

The Go memory model gives channel operations ordering guarantees. A send happens before its corresponding receive completes, and closing a channel happens before a receive observes the closure. These guarantees can order accesses to shared variables across goroutines. section 8.4.2

i := 0
ch := make(chan struct{})
go func() {
    <-ch
    fmt.Println(i)
}()
i++
ch <- struct{}{}
variable increment < channel send < channel receive < variable read

The increment precedes the send, and the receive completes before the print, ordering the variable accesses. section 8.4.2

i := 0
ch := make(chan struct{}, 1)
go func() {
    i = 1
    <-ch
}()
ch <- struct{}{}
fmt.Println(i)

Here the buffered send can complete before the other goroutine writes i, so printing i races with that write. section 8.4.2

i := 0
ch := make(chan struct{})   #1
go func() {
    i = 1
    <-ch
}()
ch <- struct{}{}
fmt.Println(i)

Making the channel unbuffered synchronizes the send with the receive, ordering the write before the print. section 8.4.2

Do not rely on case order to prioritize channels in a select. When multiple communications can proceed, select chooses among them pseudo-randomly. A disconnect notification can therefore be selected while messages remain buffered. section 9.4

for {
    select {
    case v := <-messageCh:
        fmt.Println(v)
    case <-disconnectCh:
        for {                          #1
            select {
            case v := <-messageCh:     #2
                fmt.Println(v)
            default:                   #3
                fmt.Println("disconnection, return")
                return
            }
        }
    }
}

After disconnection, this version drains messages already available before returning. It is appropriate for the example where the producer sends its messages before the disconnect notification. section 9.4

For notifications, use chan struct{}. A nil channel can disable a select case. Choose buffer capacity deliberately; a size other than one should have a good reason. section 9.15

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Explains blocking, synchronization and memory ordering, then traces select and buffer-size mistakes through examples.
Examples
Traces a shared-variable race with buffered and unbuffered channels and a message consumer receiving a disconnect notification.
What you can do after
Diagnose blocking, data races and select-priority mistakes, and choose channels or mutexes for a concurrency problem.
How it connects
Connects channels to goroutines, mutexes, the Go memory model, data races and select.

Also explained in

Compare how 10 books explain channel →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.