Mutex, Once and atomic memory guarantees
Mutex, Once and atomic memory guarantees
Mutex.Unlock synchronizes before a later successful Lock on the same mutex. A failed TryLock supplies no synchronization. Once.Do ensures initialization completes before callers return normally. Atomic operations are sequentially consistent; when atomic operation B observes A, A synchronizes before B.
package main
import ( "fmt" "sync")
func main() { var once sync.Once var config string var wg sync.WaitGroup results := make(chan string, 2) for i := 0; i < 2; i++ { wg.Add(1) go func() { defer wg.Done(); once.Do(func() { config = "v1" }); results <- config }() } wg.Wait() close(results) for s := range results { fmt.Println(s) }}The initialization function runs once, and both workers read after Do returns. Do not copy Once or Mutex after first use. If the Once function panics, it is still considered called; recovery does not establish successful initialization.
Expected output:
v1v1Atomic publication flag
package main
import ( "fmt" "runtime" "sync/atomic")
func main() { var ready atomic.Bool var value int go func() { value = 64; ready.Store(true) }() for !ready.Load() { runtime.Gosched() } fmt.Println(value)}The load reading true observes the store. The ordinary write precedes that store and the final read follows the successful load. This is a one-shot flag; later mutations need protection. The spin loop illustrates ordering, not recommended waiting: prefer channels or Once for blocking waits. Gosched is a scheduling hint, not synchronization.
Expected output:
64Try it locally
Lock a shared counter in each of four workers, increment it and wait. Print 4.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Memory model 06: Mutex, Once and atomic memory guarantees
Check the lesson objective before moving on.
Does a failed TryLock establish a memory ordering guarantee?
What allows reading value after ready.Load returns true?