Last active
November 18, 2021 11:10
-
-
Save avivklas/09cc2e7488cb6d58bd1aece64203a507 to your computer and use it in GitHub Desktop.
This file contains 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
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