Skip to content

Instantly share code, notes, and snippets.

@dbehnke
Created June 23, 2014 21:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dbehnke/93d692ff08a3d2e17a48 to your computer and use it in GitHub Desktop.
Save dbehnke/93d692ff08a3d2e17a48 to your computer and use it in GitHub Desktop.
Multiple go routines handling a single channel.
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