wait_time.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. nano := deadline.UnixNano()
  40. ch := tl.m[nano]
  41. if ch == nil {
  42. ch = make(chan struct{})
  43. tl.m[nano] = ch
  44. }
  45. return ch
  46. }
  47. func (tl *timeList) Trigger(deadline time.Time) {
  48. tl.l.Lock()
  49. defer tl.l.Unlock()
  50. for t, ch := range tl.m {
  51. if t < deadline.UnixNano() {
  52. delete(tl.m, t)
  53. close(ch)
  54. }
  55. }
  56. }