-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlock.go
72 lines (60 loc) · 1.13 KB
/
lock.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
package tlock
import (
"sync"
"sync/atomic"
"time"
)
type Lock interface {
sync.Locker
TryLock() bool
TryLockWithTimeout(duration time.Duration) bool
}
type lock struct {
lockChan chan struct{}
locked int32
}
func New() Lock {
// Create the channel with size 1
return &lock{lockChan: make(chan struct{}, 1)}
}
func (l *lock) TryLock() bool {
select {
case l.lockChan <- struct{}{}:
atomic.StoreInt32(&l.locked, 1)
return true
default:
// Failed to Acquire l
return false
}
}
func (l *lock) TryLockWithTimeout(timeout time.Duration) bool {
// fast path
if l.TryLock() {
return true
}
// slow path
select {
case l.lockChan <- struct{}{}:
atomic.StoreInt32(&l.locked, 1)
return true
case <-time.After(timeout):
if atomic.LoadInt32(&l.locked) == 0 && len(l.lockChan) == 1{
atomic.StoreInt32(&l.locked, 1)
return true
}
return false
}
}
// lock is blocking call, waits for other lockChan to be released
func (l *lock) Lock() {
l.lockChan <- struct{}{}
atomic.StoreInt32(&l.locked, 1)
}
func (l *lock) Unlock() {
select {
case <-l.lockChan:
default:
}
atomic.StoreInt32(&l.locked, 0)
return
}