Created
June 23, 2014 21:10
-
-
Save dbehnke/93d692ff08a3d2e17a48 to your computer and use it in GitHub Desktop.
Multiple go routines handling a single channel.
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 | |
//http://play.golang.org/p/kLmBrJYchH | |
import ( | |
"fmt" | |
"time" | |
) | |
func mychan(id string, c chan string) { | |
for { | |
s, ok := <-c | |
if !ok { | |
fmt.Printf("[%s] Go routine stop\n", id) | |
return | |
} | |
fmt.Printf("[%s] hi %s!\n", id, s) | |
} | |
} | |
func main() { | |
ch := make(chan string) | |
goroutineids := []string{"alpha", "bravo", "charlie", "delta"} | |
for _, id := range goroutineids { | |
go mychan(id, ch) | |
} | |
for i := 0; i < 10; i++ { | |
ch <- fmt.Sprintf("test %d", i) | |
} | |
time.Sleep(1000) | |
close(ch) | |
time.Sleep(1000) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment