wait.go 1.2 KB

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