forked from momiji/kpx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmre.go
77 lines (68 loc) · 1.64 KB
/
mre.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
73
74
75
76
77
package kpx
import (
"context"
"sync"
)
// ManualResetEvent notifies one or more waiting goroutines that an event has occurred.
//
// Once it has been signaled, ManualResetEvent remains signaled until it is manually reset.
// When signaled, all waiting goroutines are released, and all calls to Wait return immediately.
type ManualResetEvent struct {
l sync.Mutex
c chan struct{}
}
// NewManualResetEvent returns a new ManualResetEvent with initial state s
func NewManualResetEvent(s bool) *ManualResetEvent {
e := ManualResetEvent{
c: make(chan struct{}),
}
if s {
close(e.c)
}
return &e
}
// Signal sets the state of e to signaled, waking one or more waiting goroutines.
func (e *ManualResetEvent) Signal() {
e.l.Lock()
defer e.l.Unlock()
select {
case <-e.c: //ch is closed
default:
close(e.c)
}
}
// Reset sets the state of e to nonsignaled.
func (e *ManualResetEvent) Reset() {
e.l.Lock()
defer e.l.Unlock()
select {
case <-e.c: //ch is closed
e.c = make(chan struct{})
default:
}
}
// Wait suspends execution of the calling goroutine until e receives a signal.
func (e *ManualResetEvent) Wait() {
<-e.c
}
// WaitContext suspends execution of the calling goroutine until e receives a signal, or until the context is cancelled.
// The returned error is nil if e received a signal, or ctx.Err()
func (e *ManualResetEvent) WaitContext(ctx context.Context) error {
select {
case <-ctx.Done():
return ctx.Err()
case <-e.c:
return nil
}
}
func (e *ManualResetEvent) Channel() chan struct{} {
return e.c
}
func (e *ManualResetEvent) IsSignaled() bool {
select {
case <-e.c: // ch is closed
return true
default:
return false
}
}