-
-
Save mytholog/41e39b8cba0c5974eeb4d63ccc289f98 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func batcher[T any](in chan T, out chan []T, batchSize int, timeout time.Duration) { | |
for { | |
batch := make([]T, 0, batchSize) | |
t := time.After(timeout) | |
for batchReady := false; !batchReady; { | |
select { | |
case e := <-in: | |
batch = append(batch, e) | |
if len(batch) == batchSize { | |
batchReady = true | |
} | |
case <-t: | |
if len(batch) > 0 { | |
batchReady = true | |
break | |
} | |
t = time.After(timeout) | |
} | |
if batchReady == true { | |
out <- batch | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment