wait.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /*
  2. Copyright 2014 CoreOS, Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package wait
  14. import (
  15. "sync"
  16. )
  17. type Wait interface {
  18. Register(id uint64) <-chan interface{}
  19. Trigger(id uint64, x interface{})
  20. }
  21. type List struct {
  22. l sync.Mutex
  23. m map[uint64]chan interface{}
  24. }
  25. func New() *List {
  26. return &List{m: make(map[uint64]chan interface{})}
  27. }
  28. func (w *List) Register(id uint64) <-chan interface{} {
  29. w.l.Lock()
  30. defer w.l.Unlock()
  31. ch := w.m[id]
  32. if ch == nil {
  33. ch = make(chan interface{}, 1)
  34. w.m[id] = ch
  35. }
  36. return ch
  37. }
  38. func (w *List) Trigger(id uint64, x interface{}) {
  39. w.l.Lock()
  40. ch := w.m[id]
  41. delete(w.m, id)
  42. w.l.Unlock()
  43. if ch != nil {
  44. ch <- x
  45. close(ch)
  46. }
  47. }