Created
May 14, 2016 06:58
-
-
Save yanmhlv/8044f9fc943dbaaa4dc0e4460c3bb7fb to your computer and use it in GitHub Desktop.
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 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