vitess.io/vitess@v0.16.2/go/sync2/batcher.go (about) 1 /* 2 Copyright 2019 The Vitess Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package sync2 18 19 import ( 20 "time" 21 ) 22 23 // Batcher delays concurrent operations for a configurable interval in order to 24 // batch them up or otherwise clock their operation to run concurrently. 25 // 26 // It is implemented as a channel of int32s. Each waiter blocks on the channel 27 // from which it gets a sequentially increasing batch ID when the timer elapses. 28 // 29 // Hence a waiter is delayed for at most the batch interval. 30 type Batcher struct { 31 interval time.Duration 32 queue chan int 33 waiters AtomicInt32 34 nextID AtomicInt32 35 after func(time.Duration) <-chan time.Time 36 } 37 38 // NewBatcher returns a new Batcher 39 func NewBatcher(interval time.Duration) *Batcher { 40 return &Batcher{ 41 interval: interval, 42 queue: make(chan int), 43 waiters: NewAtomicInt32(0), 44 nextID: NewAtomicInt32(0), 45 after: time.After, 46 } 47 } 48 49 // newBatcherForTest returns a Batcher for testing where time.After can 50 // be replaced by a fake alternative. 51 func newBatcherForTest(interval time.Duration, after func(time.Duration) <-chan time.Time) *Batcher { 52 return &Batcher{ 53 interval: interval, 54 queue: make(chan int), 55 waiters: NewAtomicInt32(0), 56 nextID: NewAtomicInt32(0), 57 after: after, 58 } 59 } 60 61 // Wait adds a new waiter to the queue and blocks until the next batch 62 func (b *Batcher) Wait() int { 63 numWaiters := b.waiters.Add(1) 64 if numWaiters == 1 { 65 b.newBatch() 66 } 67 return <-b.queue 68 } 69 70 // newBatch starts a new batch 71 func (b *Batcher) newBatch() { 72 go func() { 73 <-b.after(b.interval) 74 75 id := b.nextID.Add(1) 76 77 // Make sure to atomically reset the number of waiters to make 78 // sure that all incoming requests either make it into the 79 // current batch or the next one. 80 waiters := b.waiters.Get() 81 for !b.waiters.CompareAndSwap(waiters, 0) { 82 waiters = b.waiters.Get() 83 } 84 85 for i := int32(0); i < waiters; i++ { 86 b.queue <- int(id) 87 } 88 }() 89 }