wait_time.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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
  15. import (
  16. "sync"
  17. "time"
  18. )
  19. type WaitTime interface {
  20. // Wait returns a chan that waits on the given deadline.
  21. // The chan will be triggered when Trigger is called with a
  22. // deadline that is later than the one it is waiting for.
  23. // The given deadline MUST be unique. The deadline should be
  24. // retrieved by calling time.Now() in most cases.
  25. Wait(deadline time.Time) <-chan struct{}
  26. // Trigger triggers all the waiting chans with an earlier deadline.
  27. Trigger(deadline time.Time)
  28. }
  29. type timeList struct {
  30. l sync.Mutex
  31. m map[int64]chan struct{}
  32. }
  33. func NewTimeList() *timeList {
  34. return &timeList{m: make(map[int64]chan struct{})}
  35. }
  36. func (tl *timeList) Wait(deadline time.Time) <-chan struct{} {
  37. tl.l.Lock()
  38. defer tl.l.Unlock()
  39. ch := make(chan struct{}, 1)
  40. // The given deadline SHOULD be unique but CI manages to get
  41. // the same nano time in the unit tests.
  42. nano := deadline.UnixNano()
  43. for {
  44. if tl.m[nano] == nil {
  45. tl.m[nano] = ch
  46. break
  47. }
  48. nano++
  49. }
  50. return ch
  51. }
  52. func (tl *timeList) Trigger(deadline time.Time) {
  53. tl.l.Lock()
  54. defer tl.l.Unlock()
  55. for t, ch := range tl.m {
  56. if t < deadline.UnixNano() {
  57. delete(tl.m, t)
  58. close(ch)
  59. }
  60. }
  61. }