-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsync.go
More file actions
54 lines (45 loc) · 1.06 KB
/
sync.go
File metadata and controls
54 lines (45 loc) · 1.06 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
package contextaware
import (
"context"
"sync"
)
// A Locker is a context-aware Locker.
type Locker interface {
LockContext(context.Context) error
Unlock()
}
// A Mutex implements the contextaware.Locker and io.Locker interfaces. It is *not* reentrant.
type Mutex struct {
once sync.Once
ch chan struct{}
}
// Lock locks the mutex using the background context.
func (mu *Mutex) Lock() {
_ = mu.LockContext(context.Background())
}
// LockContext locks the mutex. If `ctx.Done()` fires before a lock is acquired an error will be returned. If the lock
// was successfully taken, nil will be returned.
func (mu *Mutex) LockContext(ctx context.Context) error {
mu.init()
select {
case <-ctx.Done():
return ctx.Err()
case <-mu.ch:
return nil
}
}
// Unlock unlocks the mutex. Only a locked mutex may be unlocked.
func (mu *Mutex) Unlock() {
mu.init()
select {
case mu.ch <- struct{}{}:
default:
panic("contextaware: unlock of unlocked mutex")
}
}
func (mu *Mutex) init() {
mu.once.Do(func() {
mu.ch = make(chan struct{}, 1)
mu.ch <- struct{}{}
})
}