Concurrency Basics
Mutex Section
A sync.Mutex marks the critical section that changes shared state.
Mutex Section
mutex_section.go
package main
import (
"fmt"
"sync"
)
func main() {
var bonus =
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 =
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 =
var mutex sync.Mutex
total := 10
mutex.Lock()
total += bonus
mutex.Unlock()
fmt.Println("bonus=", bonus)
fmt.Println("total=", total)
fmt.Println("lockedSection=", true)
}
mutex
A mutex makes a critical section explicit so only one flow should update shared state at a time.