Skip to content

Instantly share code, notes, and snippets.

@kakaLQY
Last active February 6, 2023 10:33
Show Gist options
  • Save kakaLQY/713356f2aec4a257080cc876a6297fce to your computer and use it in GitHub Desktop.
Save kakaLQY/713356f2aec4a257080cc876a6297fce to your computer and use it in GitHub Desktop.
Golang batch get from buffered channel with a maximum number.
package testbatch
import (
"testing"
"time"
)
func TestBatch(t *testing.T) {
bufCh := make(chan int, 20)
go func() {
for {
var items []int
items = append(items, <-bufCh)
// As we need to batch get maximum 10 items, 9 remains to get.
remains := 9
Remaining:
for i := 0; i < remains; i++ {
select {
case item := <-bufCh:
items = append(items, item)
default:
break Remaining
}
}
// The batch processing. Here we just log output.
t.Log("Items:", items)
}
}()
for i := 0; i < 50; i++ {
bufCh <- i
t.Log("Push:", i)
}
time.Sleep(time.Second)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment