batcher.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /*
  2. Copyright 2019 The Vitess Authors.
  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 sync
  14. import (
  15. "time"
  16. )
  17. // Batcher delays concurrent operations for a configurable interval in order to
  18. // batch them up or otherwise clock their operation to run concurrently.
  19. //
  20. // It is implemented as a channel of int32s. Each waiter blocks on the channel
  21. // from which it gets a sequentially increasing batch ID when the timer elapses.
  22. //
  23. // Hence a waiter is delayed for at most the batch interval.
  24. type Batcher struct {
  25. interval time.Duration
  26. queue chan int
  27. waiters AtomicInt32
  28. nextID AtomicInt32
  29. after func(time.Duration) <-chan time.Time
  30. }
  31. // NewBatcher returns a new Batcher
  32. func NewBatcher(interval time.Duration) *Batcher {
  33. return &Batcher{
  34. interval: interval,
  35. queue: make(chan int),
  36. waiters: NewAtomicInt32(0),
  37. nextID: NewAtomicInt32(0),
  38. after: time.After,
  39. }
  40. }
  41. // newBatcherForTest returns a Batcher for testing where time.After can
  42. // be replaced by a fake alternative.
  43. func newBatcherForTest(interval time.Duration, after func(time.Duration) <-chan time.Time) *Batcher {
  44. return &Batcher{
  45. interval: interval,
  46. queue: make(chan int),
  47. waiters: NewAtomicInt32(0),
  48. nextID: NewAtomicInt32(0),
  49. after: after,
  50. }
  51. }
  52. // Wait adds a new waiter to the queue and blocks until the next batch
  53. func (b *Batcher) Wait() int {
  54. numWaiters := b.waiters.Add(1)
  55. if numWaiters == 1 {
  56. b.newBatch()
  57. }
  58. return <-b.queue
  59. }
  60. // newBatch starts a new batch
  61. func (b *Batcher) newBatch() {
  62. go func() {
  63. <-b.after(b.interval)
  64. id := b.nextID.Add(1)
  65. // Make sure to atomically reset the number of waiters to make
  66. // sure that all incoming requests either make it into the
  67. // current batch or the next one.
  68. waiters := b.waiters.Get()
  69. for !b.waiters.CompareAndSwap(waiters, 0) {
  70. waiters = b.waiters.Get()
  71. }
  72. for i := int32(0); i < waiters; i++ {
  73. b.queue <- int(id)
  74. }
  75. }()
  76. }