wait_time.go 1.6 KB

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