-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmutex.go
95 lines (73 loc) · 1.47 KB
/
mutex.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package main
import (
"fmt"
"sync"
"sync/atomic"
"time"
)
const (
locked int32 = 1
unlocked int32 = 0
)
type myMutex struct {
locked int32 // 1 -locked, 0 -unlocked
}
func (m *myMutex) Lock() {
// if locked, then busywait
for !atomic.CompareAndSwapInt32(&(m.locked), unlocked, locked) {
// and try to lock atomically
// func CompareAndSwapInt32(addr *int32, old, new int32) (swapped bool)
// if the value in memory matches old, write new into addr
//sleep
time.Sleep(10 * time.Millisecond)
}
}
func (m *myMutex) Unlock() {
// if mutex is already unlocked, it is a runtime error
if !atomic.CompareAndSwapInt32(&(m.locked), locked, unlocked) {
panic("trying to unlock mutex which is already unlocked")
}
}
const (
numGoroutines = 1000
numIncrements = 1000
)
var globalLock myMutex
type counter struct {
count int
}
func safeIncrement(c *counter) {
// globalLock.Lock()
// defer globalLock.Unlock()
// c.count += 1
// cond.L.lock
//
c.count += 1
//cond.L.unlock
//cond.signal
}
const (
mutexLocked = 1 << iota // mutex is locked
mutexWoken
mutexStarving
mutexWaiterShift = iota
)
// changed to global mutex usage
func main() {
fmt.Println(mutexLocked, mutexWoken, mutexStarving, mutexWaiterShift)
c := &counter{
count: 0,
}
var wg sync.WaitGroup
for i := 0; i < numGoroutines; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for j := 0; j < numIncrements; j++ {
safeIncrement(c)
}
}()
}
wg.Wait()
//fmt.Println(c.count)
}