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
|
package missinggo
import "sync"
// Events are boolean flags that provide a channel that's closed when true.
// This could go in the sync package, but that's more of a debug wrapper on
// the standard library sync.
type Event struct {
ch chan struct{}
closed bool
}
func (me *Event) LockedChan(lock sync.Locker) <-chan struct{} {
lock.Lock()
ch := me.C()
lock.Unlock()
return ch
}
// Returns a chan that is closed when the event is true.
func (me *Event) C() <-chan struct{} {
if me.ch == nil {
me.ch = make(chan struct{})
}
return me.ch
}
// TODO: Merge into Set.
func (me *Event) Clear() {
if me.closed {
me.ch = nil
me.closed = false
}
}
// Set the event to true/on.
func (me *Event) Set() (first bool) {
if me.closed {
return false
}
if me.ch == nil {
me.ch = make(chan struct{})
}
close(me.ch)
me.closed = true
return true
}
// TODO: Change to Get.
func (me *Event) IsSet() bool {
return me.closed
}
func (me *Event) Wait() {
<-me.C()
}
// TODO: Merge into Set.
func (me *Event) SetBool(b bool) {
if b {
me.Set()
} else {
me.Clear()
}
}
|