Created
September 21, 2018 20:01
-
-
Save heyimalex/cb1b8fd2feac76f4fedc0e2d80c9a614 to your computer and use it in GitHub Desktop.
batching channel implementation
This file contains hidden or 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 batchchan | |
import "github.com/cheekybits/genny/generic" | |
import ( | |
"fmt" | |
) | |
type T generic.Type | |
func batchTChan( | |
inputc <-chan T, | |
outputc chan []T, | |
batchsize int, | |
) { | |
if batchsize <= 1 { | |
panic(fmt.Sprintf("invalid batch size: %d", batchsize)) | |
} | |
var values []T | |
Main: | |
for { | |
v, ok := <-inputc | |
if !ok { | |
return | |
} | |
values = append(values, v) | |
Consume: | |
for len(values) < batchsize { | |
select { | |
case v, ok := <-inputc: | |
if !ok { | |
break Main | |
} | |
values = append(values, v) | |
continue Consume | |
default: | |
} | |
select { | |
case v, ok := <-inputc: | |
if !ok { | |
break Main | |
} | |
values = append(values, v) | |
continue Consume | |
case outputc <- values: | |
values = nil | |
continue Main | |
} | |
} | |
outputc <- values | |
values = nil | |
} | |
outputc <- values | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment