Skip to content

Instantly share code, notes, and snippets.

@yanmhlv
Created May 14, 2016 06:58
Show Gist options
  • Save yanmhlv/8044f9fc943dbaaa4dc0e4460c3bb7fb to your computer and use it in GitHub Desktop.
Save yanmhlv/8044f9fc943dbaaa4dc0e4460c3bb7fb to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"math/rand"
)
func main() {
doneCh := make(chan bool)
worker := func(n int, msgQueue chan int, printChan chan<- string, doneChan <-chan bool) {
for {
msgData := rand.Intn(10)
select {
case msg := <-msgQueue:
printChan <- fmt.Sprintln(n, "receive", msg)
case msgQueue <- msgData:
printChan <- fmt.Sprintln(n, "send", msgData)
case <-doneCh:
return
}
}
}
printWorker := func(printChan <-chan string, doneChan <-chan bool) {
for {
select {
case <-doneCh:
return
case msg := <-printChan:
fmt.Print(msg)
}
}
}
msgChan := make(chan int)
printChan := make(chan string)
for i := 0; i < 10; i++ {
go worker(i, msgChan, printChan, doneCh)
}
go printWorker(printChan, doneCh)
<-doneCh
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment