wait_time.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /*
  2. Copyright 2015 CoreOS, Inc.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package wait
  14. import (
  15. "sync"
  16. "time"
  17. )
  18. type WaitTime interface {
  19. // Wait returns a chan that waits on the given deadline.
  20. // The chan will be triggered when Trigger is called with a
  21. // deadline that is later than the one it is waiting for.
  22. // The given deadline MUST be unique. The deadline should be
  23. // retrived by calling time.Now() in most cases.
  24. Wait(deadline time.Time) <-chan struct{}
  25. // Trigger triggers all the waiting chans with an earlier deadline.
  26. Trigger(deadline time.Time)
  27. }
  28. type timeList struct {
  29. l sync.Mutex
  30. m map[int64]chan struct{}
  31. }
  32. func NewTimeList() *timeList {
  33. return &timeList{m: make(map[int64]chan struct{})}
  34. }
  35. func (tl *timeList) Wait(deadline time.Time) <-chan struct{} {
  36. tl.l.Lock()
  37. defer tl.l.Unlock()
  38. ch := make(chan struct{}, 1)
  39. // The given deadline SHOULD be unique.
  40. tl.m[deadline.UnixNano()] = ch
  41. return ch
  42. }
  43. func (tl *timeList) Trigger(deadline time.Time) {
  44. tl.l.Lock()
  45. defer tl.l.Unlock()
  46. for t, ch := range tl.m {
  47. if t < deadline.UnixNano() {
  48. delete(tl.m, t)
  49. close(ch)
  50. }
  51. }
  52. }