golang:协程通信小case
题目:
A协程只输出0;
B协程只输出奇数;
C协程只输出偶数;
三个协程完成协程间通信:
例:PrintNumber(5)
输出:0 1 0 2 0 3 0 4 0 5
package test
import (
"fmt"
"testing"
)
func PrintNumber(n int){
ch := make(chan bool, n)
inOdd := make(chan int, n)
inEven := make(chan int, n)
exitChan := make(chan bool, n)
go printZero(ch, inEven, inOdd, n, exitChan)
go printEven(inEven, ch)
go printOdd(inOdd, ch)
for i:=0; i<n; i++ {
<- exitChan
}
}
func printZero(ch chan bool, inEven chan int, inOdd chan int, n int, exitChan chan bool){
for i:=0; i<n; i++ {
fmt.Printf("0 ")
if i%2 == 0 {
inOdd <- i+1
} else {
inEven <- i+1
}
<- ch
exitChan <- true
}
}
func printOdd(ch chan int, inZero chan bool){
for{
num := <- ch
fmt.Printf("%v ", num)
inZero <- true
}
}
func printEven(ch chan int, inZero chan bool){
for{
num := <- ch
fmt.Printf("%v ", num)
inZero <- true
}
}
func TestChan(t *testing.T){
PrintNumber(10)
}