wait.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. IsRegistered(id uint64) bool
  25. }
  26. type List struct {
  27. l sync.Mutex
  28. m map[uint64]chan interface{}
  29. }
  30. func New() *List {
  31. return &List{m: make(map[uint64]chan interface{})}
  32. }
  33. func (w *List) Register(id uint64) <-chan interface{} {
  34. w.l.Lock()
  35. defer w.l.Unlock()
  36. ch := w.m[id]
  37. if ch == nil {
  38. ch = make(chan interface{}, 1)
  39. w.m[id] = ch
  40. } else {
  41. log.Panicf("dup id %x", id)
  42. }
  43. return ch
  44. }
  45. func (w *List) Trigger(id uint64, x interface{}) {
  46. w.l.Lock()
  47. ch := w.m[id]
  48. delete(w.m, id)
  49. w.l.Unlock()
  50. if ch != nil {
  51. ch <- x
  52. close(ch)
  53. }
  54. }
  55. func (w *List) IsRegistered(id uint64) bool {
  56. w.l.Lock()
  57. defer w.l.Unlock()
  58. _, ok := w.m[id]
  59. return ok
  60. }
  61. type waitWithResponse struct {
  62. ch <-chan interface{}
  63. }
  64. func NewWithResponse(ch <-chan interface{}) Wait {
  65. return &waitWithResponse{ch: ch}
  66. }
  67. func (w *waitWithResponse) Register(id uint64) <-chan interface{} {
  68. return w.ch
  69. }
  70. func (w *waitWithResponse) Trigger(id uint64, x interface{}) {}
  71. func (w *waitWithResponse) IsRegistered(id uint64) bool {
  72. panic("waitWithResponse.IsRegistered() shouldn't be called")
  73. }