-
Notifications
You must be signed in to change notification settings - Fork 1
/
rmx.go
executable file
·89 lines (74 loc) · 1.6 KB
/
rmx.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
package rmx
import (
"errors"
"runtime"
"sync"
"time"
"github.com/vxcontrol/rmx/goid"
)
// Mutex goroutine-bound mutex implementation
type Mutex struct {
// IsGeneric determines if slow (but probably more guaranteed way) goroutine ID detection
// process should be used
IsGeneric bool
// TimeWaitMS defines period between mutex state checks
TimeWaitMS time.Duration
mutex sync.Mutex
currentGoRoutine int64
lockCount uint64
}
var (
ErrAlreadyUnlocked = errors.New("Goroutine already unlocked")
ErrOtherGoroutineLocked = errors.New("Other goroutine already take the lock")
)
func (m *Mutex) getRoutineID() int64 {
if m.IsGeneric {
return goid.SlowGet()
}
return goid.Get()
}
func (m *Mutex) wait() {
switch twait := m.TimeWaitMS; {
case twait == 0:
time.Sleep(time.Millisecond)
case twait > 0:
time.Sleep(time.Millisecond * m.TimeWaitMS)
default:
}
}
// Lock locks state of the current goroutine
func (m *Mutex) Lock() {
goRoutineID := m.getRoutineID()
for {
m.mutex.Lock()
if m.currentGoRoutine == 0 {
m.currentGoRoutine = goRoutineID
break
}
if m.currentGoRoutine == goRoutineID {
break
}
m.mutex.Unlock()
runtime.Gosched()
m.wait()
}
m.lockCount++
m.mutex.Unlock()
}
// Unlock unlocks state of the current goroutine
func (m *Mutex) Unlock() error {
goRoutineID := m.getRoutineID()
m.mutex.Lock()
defer m.mutex.Unlock()
if m.currentGoRoutine == 0 {
return ErrAlreadyUnlocked
}
if m.currentGoRoutine != goRoutineID {
return ErrOtherGoroutineLocked
}
m.lockCount--
if m.lockCount == 0 {
m.currentGoRoutine = 0
}
return nil
}