Buffered channel synchronization rules
Buffered channel synchronization rules
For capacity C, receive number k synchronizes before send k+C completes. For capacity two, the first receive precedes completion of the third send, not necessarily the first or second. Numbering starts at one.
package main
import ( "fmt")
func main() { c := make(chan int, 2) c <- 1 c <- 2 var released int go func() { released = 9; <-c }() c <- 3 fmt.Println(released)}The first receive frees a slot for the third send. The worker writes released before receiving, so main can safely read it after the third send completes. Queue length is not needed for this proof.
Expected output:
9Capacity one as an exclusive token
package main
import ( "fmt" "sync")
func main() { slots := make(chan struct{}, 1) var wg sync.WaitGroup total := 0 for i := 0; i < 4; i++ { wg.Add(1) go func() { defer wg.Done(); slots <- struct{}{}; total++; <-slots }() } wg.Wait() fmt.Println(total)}Each worker acquires by sending and releases by receiving. With capacity one the previous release orders the next acquisition; critical sections cannot overlap. Larger capacities limit concurrency but do not protect a shared counter. Release on every exit path, often using defer.
Expected output:
4Try it locally
Fill a capacity-one channel; in a worker assign 15 before receiving. Send a second value and then print the assignment.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Memory model 05: Buffered channel synchronization rules
Check the lesson objective before moving on.
For capacity 3, which send completion follows receive 2?
Why is a capacity-two semaphore not a mutex?