Last active
July 22, 2024 20:18
-
-
Save kakaLQY/713356f2aec4a257080cc876a6297fce to your computer and use it in GitHub Desktop.
Golang batch get from buffered channel with a maximum number.
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 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