Skip to content

Instantly share code, notes, and snippets.

@avivklas
Last active November 18, 2021 11:10
Show Gist options
  • Save avivklas/09cc2e7488cb6d58bd1aece64203a507 to your computer and use it in GitHub Desktop.
Save avivklas/09cc2e7488cb6d58bd1aece64203a507 to your computer and use it in GitHub Desktop.
package coalescing
import (
"context"
"sync/atomic"
)
func Q(ctx context.Context, bufferSize int, fn func()) func() {
var (
q = make(chan int64, bufferSize)
v int64
)
go func() {
for {
select {
case n := <-q:
if v > n {
continue
}
fn()
case <-ctx.Done():
return
}
}
}()
return func() {
q <- atomic.AddInt64(&v, 1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment