wait.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright 2015 The etcd Authors
  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. "log"
  19. "sync"
  20. )
  21. type Wait interface {
  22. Register(id uint64) <-chan interface{}
  23. Trigger(id uint64, x interface{})
  24. }
  25. type List struct {
  26. l sync.Mutex
  27. m map[uint64]chan interface{}
  28. }
  29. func New() *List {
  30. return &List{m: make(map[uint64]chan interface{})}
  31. }
  32. func (w *List) Register(id uint64) <-chan interface{} {
  33. w.l.Lock()
  34. defer w.l.Unlock()
  35. ch := w.m[id]
  36. if ch == nil {
  37. ch = make(chan interface{}, 1)
  38. w.m[id] = ch
  39. } else {
  40. log.Panicf("dup id %x", id)
  41. }
  42. return ch
  43. }
  44. func (w *List) Trigger(id uint64, x interface{}) {
  45. w.l.Lock()
  46. ch := w.m[id]
  47. delete(w.m, id)
  48. w.l.Unlock()
  49. if ch != nil {
  50. ch <- x
  51. close(ch)
  52. }
  53. }
  54. type waitWithResponse struct {
  55. ch <-chan interface{}
  56. }
  57. func NewWithResponse(ch <-chan interface{}) Wait {
  58. return &waitWithResponse{ch: ch}
  59. }
  60. func (w *waitWithResponse) Register(id uint64) <-chan interface{} {
  61. return w.ch
  62. }
  63. func (w *waitWithResponse) Trigger(id uint64, x interface{}) {}