generated from dogmatiq/template-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mutex.go
61 lines (53 loc) · 1.17 KB
/
mutex.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 cosyne
import (
"context"
"sync"
)
// Mutex is a context-aware mutex.
type Mutex struct {
once sync.Once
guard chan struct{} // buffered guard, write = lock, read = unlock
}
// Lock acquires an exclusive lock on the mutex.
//
// It blocks until the mutex is acquired, or ctx is canceled.
func (m *Mutex) Lock(ctx context.Context) error {
m.once.Do(func() {
m.guard = make(chan struct{}, 1)
})
select {
case m.guard <- struct{}{}: // lock the mutex
return nil
case <-ctx.Done():
return ctx.Err()
}
}
// TryLock acquires an exclusive lock on the mutex if doing so would not block.
//
// It returns true if the mutex was locked successfully, or false if it was
// already locked.
func (m *Mutex) TryLock() bool {
m.once.Do(func() {
m.guard = make(chan struct{}, 1)
})
select {
case m.guard <- struct{}{}: // lock the mutex
return true
default:
return false
}
}
// Unlock releases the mutex.
//
// It panics if the mutex is not currently locked.
func (m *Mutex) Unlock() {
m.once.Do(func() {
m.guard = make(chan struct{}, 1)
})
select {
case <-m.guard: // unlock the mutex
return // keep to see coverage
default:
panic("mutex is not locked")
}
}