Trace channel buffers and wait queues
Trace channel buffers and wait queues
In Go 1.23, a channel has runtime metadata for queued values, capacity, a circular buffer, read/write positions and sender/receiver wait queues. An unbuffered channel transfers a value when sender and receiver rendezvous. A buffered channel can accept values while space exists. If an operation cannot proceed, its goroutine may park until another operation makes progress. The runtime protects channel state internally; this does not protect unrelated shared variables. Channel FIFO value order is distinct from a guarantee about which waiting goroutine runs first.
package main
import ( "fmt")
func main() { ch := make(chan int, 2) ch <- 10 ch <- 20 fmt.Println(len(ch), cap(ch)) fmt.Println(<-ch) ch <- 30 fmt.Println(<-ch, <-ch) close(ch) v, ok := <-ch fmt.Println(v, ok)}The send of 30 follows a receive that frees one slot. Reading the remaining values preserves send order. After the buffer drains, a receive from the closed channel returns zero and false. len is an instantaneous queue length, not a reservation: another goroutine can change it immediately. Prefer select for nonblocking operations rather than testing len before sending.
Expected output:
2 21020 300 falseObserve readiness without relying on scheduling order
package main
import ( "fmt")
func main() { ch := make(chan int, 1) ch <- 1 select { case ch <- 2: fmt.Println("sent") default: fmt.Println("full") } fmt.Println(<-ch) select { case <-ch: fmt.Println("received") default: fmt.Println("empty") }}The default branch is chosen when no communication can proceed. In a real concurrent trace, blocked sends and receives may appear as waiting goroutines. The scheduler decides when a ready goroutine runs. Do not assume fairness or inspect private queue pointers; use a bounded test or execution trace to investigate delays.
Expected output:
full1emptyTry it locally
Use a capacity-two channel, send 4 and 5, close it from its sole sender, then drain with range and print the sum and count.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Runtime representations 03: Trace channel buffers and wait queues
Check the lesson objective before moving on.
What does len(ch) report for a buffered channel?
What is guaranteed when draining a closed buffered channel?