Analyze multi-step invariants
Analyze multi-step invariants
An invariant is a rule that must remain true for observable state. Stock must never become negative. Checking availability and subtracting stock are one logical operation; protect both under the same lock. Individually safe accesses can still produce incorrect results.
package main
import ( "fmt" "sync")
type Stock struct { mu sync.Mutex n int}
func (s *Stock) Take(n int) bool { s.mu.Lock() defer s.mu.Unlock() if n <= 0 || n > s.n { return false } s.n -= n return true}func main() { s := &Stock{n: 1} results := make(chan bool, 2) var wg sync.WaitGroup for i := 0; i < 2; i++ { wg.Add(1) go func() { defer wg.Done(); results <- s.Take(1) }() } wg.Wait() close(results) success := 0 for ok := range results { if ok { success++ } } fmt.Println(success, s.n)}Exactly one worker succeeds; its identity is unspecified. Main reads stock after both workers finish. Separate atomic check and subtraction could both observe sufficient stock; a race detector might report nothing because the individual accesses are synchronized. Reject nonpositive requests as well.
Expected output:
1 0Keep related fields consistent
package main
import ( "fmt" "sync")
type Budget struct { mu sync.Mutex free, used int}
func (b *Budget) Reserve(n int) bool { b.mu.Lock() defer b.mu.Unlock() if n <= 0 || n > b.free { return false } b.free -= n b.used += n return true}func (b *Budget) Snapshot() (int, int) { b.mu.Lock(); defer b.mu.Unlock(); return b.free, b.used }func main() { b := &Budget{free: 10} fmt.Println(b.Reserve(4)) fmt.Println(b.Reserve(7)) fmt.Println(b.Snapshot())}Both fields change and are observed under one lock. Their sum remains 10 and neither becomes negative. When multiple locks are necessary, establish consistent acquisition order to avoid circular waiting. Test business rules and failure paths in addition to race detection.
Expected output:
truefalse6 4Try it locally
Guard a seat reservation of 3 initial seats. Reject nonpositive and excessive requests. Reserve 2 twice and print true false 1.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Synchronization 09: Analyze multi-step invariants
Check the lesson objective before moving on.
Why guard check and subtraction together?
Can a race-free program violate an invariant?