Channel send, receive and close guarantees
Channel send, receive and close guarantees
A send is synchronized before its matching receive completes. Closing a channel synchronizes before a receive that reports closure (zero value and false). For an unbuffered channel there is also a reverse edge: its receive synchronizes before the matching send completes.
package main
import ( "fmt")
func main() { c := make(chan int, 1) var final string go func() { c <- 1; final = "complete"; close(c) }() fmt.Println(<-c) _, ok := <-c fmt.Println(ok, final)}The first receive sees the sent element, not necessarily the later close. Only the second receive observes closure here. Reading final before that receive would lack the required edge. A zero value sent explicitly has ok=true, unlike a closed and drained channel.
Expected output:
1false completeUnbuffered acknowledgment
package main
import ( "fmt")
func main() { c := make(chan struct{}) var value int go func() { value = 19; <-c }() c <- struct{}{} fmt.Println(value)}The worker writes before receiving; the receive orders the completion of main’s unbuffered send. Replacing the channel with capacity one breaks this reasoning: the send can finish before any receive. Use an explicit acknowledgment instead if buffering is required.
Expected output:
19Try it locally
Publish "saved" before closing a signal channel; receive the closed-channel indication before reading.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Memory model 04: Channel send, receive and close guarantees
Check the lesson objective before moving on.
Which receive observes the close after a buffered send?
What changes when the acknowledgment channel gets capacity one?