Last active
February 26, 2018 20:53
-
-
Save andriykohut/6b9a311bdcd4ec896385cddf54f5ebdf to your computer and use it in GitHub Desktop.
Go channels - recieving results in batches
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 main | |
import ( | |
"fmt" | |
) | |
func genInts(count int) (ints chan int, quit chan bool) { | |
ints, quit = make(chan int), make(chan bool) | |
go func() { | |
defer close(ints) | |
defer close(quit) | |
i := 1 | |
for j := 1; j <= count; j++ { | |
ints <- i | |
i++ | |
} | |
quit <- true | |
}() | |
return ints, quit | |
} | |
func batches(c chan int, quit chan bool, size int) chan []int { | |
q := false | |
batch := []int{} | |
results := make(chan []int) | |
go func() { | |
defer close(results) | |
for !q { | |
select { | |
case i := <-c: | |
if len(batch) < size { | |
batch = append(batch, i) | |
} else { | |
results <- batch | |
batch = []int{i} | |
} | |
case q = <-quit: | |
results <- batch | |
} | |
} | |
}() | |
return results | |
} | |
func main() { | |
ints, quit := genInts(34) | |
for batch := range batches(ints, quit, 10) { | |
fmt.Println(batch) | |
} | |
/* | |
Prints: | |
[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] | |
*/ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment