event.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package missinggo
  2. import "sync"
  3. // Events are boolean flags that provide a channel that's closed when true.
  4. // This could go in the sync package, but that's more of a debug wrapper on
  5. // the standard library sync.
  6. type Event struct {
  7. ch chan struct{}
  8. closed bool
  9. }
  10. func (me *Event) LockedChan(lock sync.Locker) <-chan struct{} {
  11. lock.Lock()
  12. ch := me.C()
  13. lock.Unlock()
  14. return ch
  15. }
  16. // Returns a chan that is closed when the event is true.
  17. func (me *Event) C() <-chan struct{} {
  18. if me.ch == nil {
  19. me.ch = make(chan struct{})
  20. }
  21. return me.ch
  22. }
  23. // TODO: Merge into Set.
  24. func (me *Event) Clear() {
  25. if me.closed {
  26. me.ch = nil
  27. me.closed = false
  28. }
  29. }
  30. // Set the event to true/on.
  31. func (me *Event) Set() (first bool) {
  32. if me.closed {
  33. return false
  34. }
  35. if me.ch == nil {
  36. me.ch = make(chan struct{})
  37. }
  38. close(me.ch)
  39. me.closed = true
  40. return true
  41. }
  42. // TODO: Change to Get.
  43. func (me *Event) IsSet() bool {
  44. return me.closed
  45. }
  46. func (me *Event) Wait() {
  47. <-me.C()
  48. }
  49. // TODO: Merge into Set.
  50. func (me *Event) SetBool(b bool) {
  51. if b {
  52. me.Set()
  53. } else {
  54. me.Clear()
  55. }
  56. }