-
Notifications
You must be signed in to change notification settings - Fork 8
/
chan.go
61 lines (52 loc) · 1.41 KB
/
chan.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
package lock
import (
"context"
"time"
)
// ChanMutex is the struct implementing Mutex by channel.
type ChanMutex struct {
lockChan chan struct{}
}
// NewChanMutex returns ChanMutex.
func NewChanMutex() *ChanMutex {
return &ChanMutex{
lockChan: make(chan struct{}, 1),
}
}
// Lock acquires the lock.
// If it is currently held by others, Lock will wait until it has a chance to acquire it.
func (m *ChanMutex) Lock() {
m.lockChan <- struct{}{}
}
// Unlock releases the lock.
func (m *ChanMutex) Unlock() {
<-m.lockChan
}
// TryLock attempts to acquire the lock without blocking.
// Return false if someone is holding it now.
func (m *ChanMutex) TryLock() bool {
select {
case m.lockChan <- struct{}{}:
return true
default:
return false
}
}
// TryLockWithContext attempts to acquire the lock, blocking until resources
// are available or ctx is done (timeout or cancellation).
func (m *ChanMutex) TryLockWithContext(ctx context.Context) bool {
select {
case m.lockChan <- struct{}{}:
return true
case <-ctx.Done():
// timeout or cancellation
return false
}
}
// TryLockWithTimeout attempts to acquire the lock within a period of time.
// Return false if spending time is more than duration and no chance to acquire it.
func (m *ChanMutex) TryLockWithTimeout(duration time.Duration) bool {
ctx, cancel := context.WithTimeout(context.Background(), duration)
defer cancel()
return m.TryLockWithContext(ctx)
}