当你使用非缓冲通道时,通道内容将被按顺序处理,所以下一个值被阻止,直到前一个值被处理。请看下面的输出。在这个例子中,我们将使用goroutines来处理他们自己通道中的特定工作。奇数用奇数通道处理,偶数用偶数通道处理。
package main
import (
"fmt"
"math/rand"
"time"
)
var (
limit = 9
values = []int{0, 1, 2, 3, 4, 5, 6}
)
func main() {
// You can use buffered version if you wish.
chOd := make(chan int)
chEv := make(chan int)
go odd(chOd)
go even(chEv)
pick(chOd, chEv)
}
// Will write numbers to relevant channels.
func pick(chOd, chEv chan <- int) {
rand.Seed(time.Now().UnixNano())
for i := 1; i <= limit; i++ {
v := values[rand.Intn(len(values))]
fmt.Println("PIK", i, ":", v)
if v%2 != 0 {
chOd <- v
} else {
chEv <- v
}
}
}
// Will block until the channel is empty.
func odd(ch <- chan int) {
for v := range ch {
fmt.Println("ODD", v)
}
}
// Will block until the channel is empty.
func even(ch <- chan int) {
for v := range ch {
fmt.Println("EVE", v)
}
}
PIK 1 : 4
PIK 2 : 5
EVE 4
ODD 5
PIK 3 : 0
PIK 4 : 6
EVE 0
PIK 5 : 2
EVE 6
EVE 2
PIK 6 : 6
PIK 7 : 3
EVE 6
PIK 8 : 3
ODD 3
ODD 3
PIK 9 : 0
EVE 0