Last active
May 8, 2016 06:16
-
-
Save darrennoble/52c33efbb522a7e145554ea95c063498 to your computer and use it in GitHub Desktop.
Go example of joining / merging a slice of arbitrary length into one chanel
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 setupChans(count int) []chan int { | |
c := []chan int{} | |
for i := 0; i < count; i++ { | |
newChan := make(chan int) | |
c = append(c, newChan) | |
go func(num int, cn chan int) { | |
for j := 0; j < 4; j++ { | |
cn <- j*count + num | |
} | |
close(cn) | |
}(i, newChan) | |
} | |
return c | |
} | |
func joinChannels(chans []chan int) chan int { | |
joint := make(chan int) | |
closeChan := make(chan bool) | |
for _, c := range chans { | |
go func(inChan chan int) { | |
for i := range inChan { | |
joint <- i | |
} | |
closeChan <- true | |
}(c) | |
} | |
go func() { | |
for i := 0; i < len(chans); i++ { | |
<-closeChan | |
} | |
close(joint) | |
}() | |
return joint | |
} | |
func main() { | |
count := 4 | |
chans := setupChans(count) | |
master := joinChannels(chans) | |
for i := range master { | |
fmt.Printf("%v\n", i) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment