Created
October 21, 2015 15:15
-
-
Save frontierpsycho/c5704de18f51ca0fae4b to your computer and use it in GitHub Desktop.
BatchChannel example
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" | |
"strings" | |
) | |
var batchSize int = 2 | |
func main() { | |
inputChannel := make(chan string, 10) | |
batchedChannel := make(chan []string) | |
quit := make(chan bool) | |
go func() { | |
for { | |
next, more := <-batchedChannel | |
fmt.Println(strings.Join(next, " ")) | |
if !more { | |
quit <- true | |
return | |
} | |
} | |
}() | |
go func() { | |
for i := 1; i <= 10; i++ { | |
inputChannel <- fmt.Sprintf("%d", i) | |
} | |
close(inputChannel) | |
}() | |
go BatchChannel(inputChannel, batchedChannel, batchSize) | |
<-quit | |
} | |
func BatchChannel(channel chan string, batchedChannel chan []string, batchSize int) { | |
buff := make([]string, 0, batchSize) | |
for { | |
next, more := <-channel | |
if more { | |
buff = append(buff, next) | |
if len(buff) >= batchSize { | |
batchedChannel <- buff | |
buff = make([]string, 0, batchSize) | |
} | |
} else { | |
if len(buff) > 0 { | |
batchedChannel <- buff | |
} | |
close(batchedChannel) | |
return | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment