A sync.Mutex marks the critical section that changes shared state.

mutex A mutex makes a critical section explicit so only one flow should update shared state at a time.

Mutex Section

bonus
mutex_section.go
Replay: real traced execution (multi-file project)
package main

import (
	"fmt"
	"sync"
)

func main() {
	var bonus = 3
	var mutex sync.Mutex
	total := 10

	mutex.Lock()
	total += bonus
	mutex.Unlock()

	fmt.Println("bonus=", bonus)
	fmt.Println("total=", total)
	fmt.Println("lockedSection=", true)
}
package main

import (
	"fmt"
	"sync"
)

func main() {
	var bonus = 1
	var mutex sync.Mutex
	total := 10

	mutex.Lock()
	total += bonus
	mutex.Unlock()

	fmt.Println("bonus=", bonus)
	fmt.Println("total=", total)
	fmt.Println("lockedSection=", true)
}
package main

import (
	"fmt"
	"sync"
)

func main() {
	var bonus = 5
	var mutex sync.Mutex
	total := 10

	mutex.Lock()
	total += bonus
	mutex.Unlock()

	fmt.Println("bonus=", bonus)
	fmt.Println("total=", total)
	fmt.Println("lockedSection=", true)
}
  1. bonus ← 3, mutex ← sync.Mutex{state:0, sema:0x0}, total ← 10

    8func main() {9  var bonus→ 3 = 3 //@bonus=1, 510  var mutex→ sync.Mutex{state:0, sema:0x0} sync.Mutex11  total→ 10 := 101213  mutex→ sync.Mutex{state:1, sema:0x0}.Lock()14  total→ 13 += bonus315  mutex→ sync.Mutex{state:0, sema:0x0}.Unlock()1617  fmt.Println("bonus=", bonus3)18  fmt.Println("total=", total13)19  fmt.Println("lockedSection=", true)20}
    outputbonus= 3
    total= 13
    lockedSection= true
  1. bonus ← 1, mutex ← sync.Mutex{state:0, sema:0x0}, total ← 10

    8func main() {9  var bonus→ 1 = 110  var mutex→ sync.Mutex{state:0, sema:0x0} sync.Mutex11  total→ 10 := 101213  mutex→ sync.Mutex{state:1, sema:0x0}.Lock()14  total→ 11 += bonus115  mutex→ sync.Mutex{state:0, sema:0x0}.Unlock()1617  fmt.Println("bonus=", bonus1)18  fmt.Println("total=", total11)19  fmt.Println("lockedSection=", true)20}
    outputbonus= 1
    total= 11
    lockedSection= true
  1. bonus ← 5, mutex ← sync.Mutex{state:0, sema:0x0}, total ← 10

    8func main() {9  var bonus→ 5 = 510  var mutex→ sync.Mutex{state:0, sema:0x0} sync.Mutex11  total→ 10 := 101213  mutex→ sync.Mutex{state:1, sema:0x0}.Lock()14  total→ 15 += bonus515  mutex→ sync.Mutex{state:0, sema:0x0}.Unlock()1617  fmt.Println("bonus=", bonus5)18  fmt.Println("total=", total15)19  fmt.Println("lockedSection=", true)20}
    outputbonus= 5
    total= 15
    lockedSection= true