Sequenced-before and synchronized-before
Sequenced-before and synchronized-before
A memory operation reads or writes a location. Sequenced-before is the ordering required by Go within a goroutine; synchronized-before connects synchronization operations, such as a channel send and its matching receive. It is not a timeline of CPU instructions.
package main
import ( "fmt")
func main() { x := 0 done := make(chan struct{}) go func() { x = 42; done <- struct{}{} }() <-done fmt.Println(x)}The write to x precedes the send within the worker. The send synchronizes with completion of the receive. The read follows the receive in main. These three edges establish the guarantee, independently of scheduling. The empty struct is just a signal.
Expected output:
42Follow the edges in the opposite direction
package main
import ( "fmt")
func main() { var name string start := make(chan struct{}) result := make(chan string) go func() { <-start; result <- name }() name = "Ada" start <- struct{}{} fmt.Println(<-result)}The assignment in main precedes start send; the worker reads only after receiving. An unrelated channel communication does not automatically order all accesses. Go specifies a partial order: some operations have no ordering relation.
Expected output:
AdaTry it locally
Write 7 in a worker and signal through a channel; print the value only after receiving.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Memory model 01: Sequenced-before and synchronized-before
Check the lesson objective before moving on.
Which edge is inter-goroutine?
Does wall-clock order establish synchronized-before?