-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathctx_locker.go
More file actions
63 lines (55 loc) · 1.18 KB
/
ctx_locker.go
File metadata and controls
63 lines (55 loc) · 1.18 KB
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
// ctx_locker.go implements CtxLocker, a channel-based synchronization primitive that supports context-aware locking.
package xsync
import (
"context"
"github.com/facebookincubator/go-belt/tool/logger"
)
// CtxLocker is a channel-based synchronization primitive that supports context-aware locking.
// TODO: move to a separate package
type CtxLocker chan struct{}
func (l CtxLocker) ManualLock(ctx context.Context) bool {
select {
case <-ctx.Done():
loggingEnabled := IsLoggingEnabled(ctx)
if loggingEnabled {
logger.Tracef(ctx, "context is closed")
}
return false
case l <- struct{}{}:
return true
}
}
func (l CtxLocker) ManualTryLock(ctx context.Context) bool {
select {
case <-ctx.Done():
loggingEnabled := IsLoggingEnabled(ctx)
if loggingEnabled {
logger.Tracef(ctx, "context is closed")
}
return false
case l <- struct{}{}:
return true
default:
return false
}
}
func (l CtxLocker) ManualUnlock(ctx context.Context) {
select {
case <-l:
default:
if IsAllowUnlockNotLocked(ctx) {
return
}
panic("not locked!")
}
}
func (l CtxLocker) Do(
ctx context.Context,
fn func(),
) {
if !l.ManualLock(ctx) {
return
}
defer l.ManualUnlock(ctx)
fn()
}