wait.go 611 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package wait
  2. import (
  3. "sync"
  4. )
  5. type Wait interface {
  6. Register(id uint64) <-chan interface{}
  7. Trigger(id uint64, x interface{})
  8. }
  9. type List struct {
  10. l sync.Mutex
  11. m map[uint64]chan interface{}
  12. }
  13. func New() *List {
  14. return &List{m: make(map[uint64]chan interface{})}
  15. }
  16. func (w *List) Register(id uint64) <-chan interface{} {
  17. w.l.Lock()
  18. defer w.l.Unlock()
  19. ch := w.m[id]
  20. if ch == nil {
  21. ch = make(chan interface{}, 1)
  22. w.m[id] = ch
  23. }
  24. return ch
  25. }
  26. func (w *List) Trigger(id uint64, x interface{}) {
  27. w.l.Lock()
  28. ch := w.m[id]
  29. delete(w.m, id)
  30. w.l.Unlock()
  31. if ch != nil {
  32. ch <- x
  33. close(ch)
  34. }
  35. }