/
event.go
63 lines (56 loc) · 1.28 KB
/
event.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
// Package event implements python's threading.Event api using golang primitives.
package event
import (
"context"
)
// Event is a communication primitive allowing for multiple goroutines to wait
// on an event to be set.
type Event struct {
next chan chan struct{}
}
// New creates a new event instance.
func New() *Event {
next := make(chan chan struct{}, 1)
next <- make(chan struct{})
return &Event{next: next}
}
// IsSet indicates whether an event is set or not.
func (r *Event) IsSet() bool {
event := <-r.next
r.next <- event
return event == nil
}
// Set changes the internal state of an event to true.
func (r *Event) Set() {
event := <-r.next
if event != nil {
close(event)
event = nil
}
r.next <- event
}
// Clear resets the internal event state back to false.
func (r *Event) Clear() {
event := <-r.next
if event == nil {
event = make(chan struct{})
}
r.next <- event
}
// Wait blocks until the event is set to true. If the event is already set,
// returns immediately. Otherwise blocks until another goroutine sets the event.
func (r *Event) Wait(ctx context.Context) error {
event := <-r.next
r.next <- event
if event != nil {
if ctx == nil {
ctx = context.Background()
}
select {
case <-ctx.Done():
return ctx.Err()
case <-event:
}
}
return nil
}