-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
58 lines (50 loc) · 1.14 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package main
import (
"fmt"
"sync"
)
// process handles the actual computation
func process(batch []int) {
fmt.Println(batch)
}
// worker handles batching up events until batchSize is reached then calls process()
func worker(wg *sync.WaitGroup, bufCh chan int, batchSize int) {
var batch []int
defer wg.Done()
for {
select {
case v, open := <-bufCh:
if open == false {
// anything left to process, finish it
if len(batch) > 0 {
process(batch)
}
return
}
batch = append(batch, v)
if len(batch) >= batchSize {
process(batch)
batch = batch[:0]
}
}
}
}
func main() {
// setup wait group so we can wait for all goroutines to complete
wg := new(sync.WaitGroup)
batchSize := 10
// create a bounded channel that will block to minimize memory
bufCh := make(chan int, batchSize)
// spawn enough workers as goroutines
for index := 0; index < 5; index++ {
fmt.Printf("started worker: %d\n", index)
go worker(wg, bufCh, batchSize)
wg.Add(1)
}
// add some integers to the channel to have batched and processed
for index := 0; index < 999; index++ {
bufCh <- index
}
close(bufCh)
wg.Wait()
}