wait.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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 provides utility functions for polling, listening using Go
  15. // channel.
  16. package wait
  17. import (
  18. "sync"
  19. )
  20. type Wait interface {
  21. Register(id uint64) <-chan interface{}
  22. Trigger(id uint64, x interface{})
  23. }
  24. type List struct {
  25. l sync.Mutex
  26. m map[uint64]chan interface{}
  27. }
  28. func New() *List {
  29. return &List{m: make(map[uint64]chan interface{})}
  30. }
  31. func (w *List) Register(id uint64) <-chan interface{} {
  32. w.l.Lock()
  33. defer w.l.Unlock()
  34. ch := w.m[id]
  35. if ch == nil {
  36. ch = make(chan interface{}, 1)
  37. w.m[id] = ch
  38. }
  39. return ch
  40. }
  41. func (w *List) Trigger(id uint64, x interface{}) {
  42. w.l.Lock()
  43. ch := w.m[id]
  44. delete(w.m, id)
  45. w.l.Unlock()
  46. if ch != nil {
  47. ch <- x
  48. close(ch)
  49. }
  50. }