Buffered channels and closing

A buffered channel holds a fixed number of values, so a send returns while there is room instead of waiting for a receiver. The buffer moves the meeting point: the producer can get a few steps ahead, and the consumer catches up later. It is not a queue that grows: make(chan T, n) has room for exactly n values, and the send blocks when they are full.

A buffer of three

The three sends below return immediately because the capacity is three. len reports how many values are waiting and cap the room that was made; both are safe to read while other goroutines use the channel, although the number may be stale the moment it is printed.

package main import "fmt" func main() { jobs := make(chan int, 3) jobs <- 1 jobs <- 2 jobs <- 3 fmt.Println("len:", len(jobs), "cap:", cap(jobs)) for i := 0; i < 3; i++ { fmt.Println("got", <-jobs) } fmt.Println("len after:", len(jobs)) }

go build -o app main.go && ./app

len: 3 cap: 3
got 1
got 2
got 3
len after: 0

The values came out in the order they went in, which a single channel always guarantees. Had the program sent a fourth value, the send would have blocked until a receive made room: a buffered channel of capacity three is a rendezvous for four parties, not a place to put an unbounded stream.

close and the two-value receive

A range ends at the close, and a two-value receive reports the same fact in one statement: the value, and whether the channel is still open. The ok form is what a loop that cannot use range needs, and it distinguishes a closed channel from a channel that sent a zero value.

package main import "fmt" func main() { ch := make(chan string, 2) ch <- "a" ch <- "b" close(ch) for { v, ok := <-ch if !ok { break } fmt.Println("value:", v) } fmt.Println("closed") }

go build -o app main.go && ./app

value: a
value: b
closed

A buffered channel keeps its values through the close, so the two values arrive before ok turns false. That is the reason a close is not a signal to throw the rest away: the receiver drains what is there and only then sees the end.

The send on a closed channel

A send after a close is a runtime panic, and the program below makes it happen on purpose so the output is the real one. The receive would have been legal: after the close, a receive returns the zero value with ok == false. Only the send is fatal, because a receiver cannot tell whether a value arrived or the producer gave up.

package main import "fmt" func main() { ch := make(chan int, 1) ch <- 1 close(ch) ch <- 2 fmt.Println("not reached") }

go build -trimpath -o app panic.go && ./app

panic: send on closed channel

goroutine 1 [running]:
main.main()
./panic.go:9 +0x56
exit status: 2

The stack says which goroutine and which line; the exit status is 2. A close of an already closed channel panics the same way with close of closed channel, which is why a close belongs to exactly one owner. A recover can catch the panic, and doing so is almost always a sign the channel ownership is wrong.

The rules of a buffer

The capacity is a number in the make call and cannot change. Every value that goes in comes out or is discarded with the channel, and a channel that is garbage collected with values still buffered loses them silently. A buffer of one is the usual way to make a signal asynchronous, and a buffer of the number of workers is the usual way to let a dispatcher get ahead without blocking on the slowest worker.

A buffer does not make a program correct, it only changes where it waits. A producer that runs ahead of the consumer fills it and blocks, a consumer that is slower than the producer drains it and waits, and neither is a bug: the size of the buffer is a statement about how much slack the design wants, and it is worth writing down why the number is what it is.

Exercises

  1. Send a fourth value to the channel of capacity three and run the program. Which goroutine blocks, and what does the runtime report if nothing ever receives?
  2. Close a channel twice and read the panic. What is the message, and how would you structure the code so only one goroutine can close it?
  3. Replace the two-value receive with a range over the same buffered channel. Which version reads better, and what does the range need that the loop does not?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does make(chan int, 3) create?

    Answer

    A channel with room for three values

    A send returns while there is room.

  2. When does a send on a full buffered channel return?

    Answer

    When a receive makes room

    The buffer is fixed and a full channel blocks.

  3. What do len and cap report for a buffered channel?

    Answer

    The values waiting and the capacity

    The values may be stale as soon as they are read.

  4. What does a receive from a closed channel return?

    Answer

    The zero value with ok == false

    The two-value form reports the close.

  5. What does a send on a closed channel do?

    Answer

    Panics with send on closed channel

    The program exits with status 2.

  6. What does a second close of the same channel do?

    Answer

    Panics with close of closed channel

    Close belongs to one owner.

  7. What happens to values still in a buffered channel when it is collected?

    Answer

    They are lost

    A channel is not persistent storage.

  8. Why is a buffer of one common for a signal?

    Answer

    It makes the send asynchronous

    The sender does not wait for the receiver.

  9. What does the capacity of a channel express?

    Answer

    How much slack the design wants between producer and consumer

    A buffer changes where the program waits.

  10. Which order do buffered values come out in?

    Answer

    The order they went in

    A single channel is a FIFO.

The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev