-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmutex.go
57 lines (47 loc) · 812 Bytes
/
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
package main
import (
"math/rand"
"sync"
)
var globalState int64
var mutex *sync.Mutex
var spinLock SpinLock
var spinLock2 SpinLockBit
func init() {
mutex = new(sync.Mutex)
spinLock = NewSpinLock()
spinLock2 = NewSpinLockBit()
}
func Calculation() {
globalState += rand.Int63n(1000)
}
func LockedWithMutex() {
mutex.Lock()
Calculation()
mutex.Unlock()
}
func LockedWithDeferMutex() {
mutex.Lock()
defer mutex.Unlock()
Calculation()
}
func LockedWithSpinLock() {
spinLock.Lock()
Calculation()
spinLock.Unlock()
}
func LockedWithDeferSpinLock() {
spinLock.Lock()
defer spinLock.Unlock()
Calculation()
}
func LockedWithSpinLockBit() {
spinLock2.Lock()
Calculation()
spinLock2.Unlock()
}
func LockedWithDeferSpinLockBit() {
spinLock2.Lock()
defer spinLock2.Unlock()
Calculation()
}