package main
import "fmt"
func odd(oddChan chan int, evenChan chan int, exitChan chan bool) {
for {
v, ok := <-oddChan
if(!ok) {
return
}
fmt.Println(v)
evenChan<- v + 1
}
close(evenChan)
exitChan<- true
}
func even(oddChan chan int, evenChan chan int, exitChan chan bool) {
for {
v, ok := <-evenChan
if(!ok) {
return
}
fmt.Println(v)
if(v == 100) {
break
}
oddChan<- v + 1
}
close(oddChan)
exitChan<- true
close(exitChan)
}
func main() {
oddChan := make(chan int, 1)
evenChan := make(chan int, 1)
exitChan := make(chan bool, 2)
oddChan<- 1;
go odd(oddChan, evenChan, exitChan)
go even(oddChan, evenChan, exitChan)
for i := 0; i < 2; i++ { // 要在遍历之前关闭chan
<- exitChan
}
return
}
感觉问题比较大