NOTE
2.8 sync.Mutex
What Mutex is and examples showing the difference between unsynchronized access and access protected by sync.Mutex.
This is a historical learning note and may contain outdated or incomplete understanding.
1. What Is Mutex
- A mutual-exclusion lock
- Implements the
Lockerinterface; its zero value is the unlocked state - Locking and unlocking can be done in different goroutines
2. Usage
2.1. Without Mutex
const TIMES = 1000
var data int = 0
func TestSync2(t *testing.T) {
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
for i := 0; i < TIMES; i++ {
data--
time.Sleep(2*time.Millisecond)
}
}()
go func() {
defer wg.Done()
for i := 0; i < TIMES; i++ {
data++
time.Sleep(time.Millisecond)
}
}()
wg.Wait()
fmt.Println(data, data == 0)
}
// output
-1 false
2.2. With Mutex
const TIMES = 1000
var data int = 0
func TestSync2(t *testing.T) {
var wg sync.WaitGroup
var lock sync.Mutex
wg.Add(2)
go func() {
defer wg.Done()
for i := 0; i < TIMES; i++ {
lock.Lock()
data--
lock.Unlock()
time.Sleep(2 * time.Millisecond)
}
}()
go func() {
defer wg.Done()
for i := 0; i < TIMES; i++ {
lock.Lock()
data++
lock.Unlock()
time.Sleep(time.Millisecond)
}
}()
wg.Wait()
fmt.Println(data, data == 0)
}
// output
0 true
Discussion
Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub