wait.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. // Wait is an interface that provides the ability to wait and trigger events that
  22. // are associated with IDs.
  23. type Wait interface {
  24. // Register waits returns a chan that waits on the given ID.
  25. // The chan will be triggered when Trigger is called with
  26. // the same ID.
  27. Register(id uint64) <-chan interface{}
  28. // Trigger triggers the waiting chans with the given ID.
  29. Trigger(id uint64, x interface{})
  30. IsRegistered(id uint64) bool
  31. }
  32. type list struct {
  33. l sync.Mutex
  34. m map[uint64]chan interface{}
  35. }
  36. // New creates a Wait.
  37. func New() Wait {
  38. return &list{m: make(map[uint64]chan interface{})}
  39. }
  40. func (w *list) Register(id uint64) <-chan interface{} {
  41. w.l.Lock()
  42. defer w.l.Unlock()
  43. ch := w.m[id]
  44. if ch == nil {
  45. ch = make(chan interface{}, 1)
  46. w.m[id] = ch
  47. } else {
  48. log.Panicf("dup id %x", id)
  49. }
  50. return ch
  51. }
  52. func (w *list) Trigger(id uint64, x interface{}) {
  53. w.l.Lock()
  54. ch := w.m[id]
  55. delete(w.m, id)
  56. w.l.Unlock()
  57. if ch != nil {
  58. ch <- x
  59. close(ch)
  60. }
  61. }
  62. func (w *list) IsRegistered(id uint64) bool {
  63. w.l.Lock()
  64. defer w.l.Unlock()
  65. _, ok := w.m[id]
  66. return ok
  67. }
  68. type waitWithResponse struct {
  69. ch <-chan interface{}
  70. }
  71. func NewWithResponse(ch <-chan interface{}) Wait {
  72. return &waitWithResponse{ch: ch}
  73. }
  74. func (w *waitWithResponse) Register(id uint64) <-chan interface{} {
  75. return w.ch
  76. }
  77. func (w *waitWithResponse) Trigger(id uint64, x interface{}) {}
  78. func (w *waitWithResponse) IsRegistered(id uint64) bool {
  79. panic("waitWithResponse.IsRegistered() shouldn't be called")
  80. }