package main import "fmt" func Producer(ch chan int) { for i := 1; i <= 10; i++ { ch <- i } close(ch) } func Consumer(id int, ch chan int, done chan bool) { for { value, ok := <-ch if ok { fmt.Printf("id: %d, recv: %d ", id, value) } else { fmt.Printf("id: %d, closed ", id) break } } done <- true } func main() { ch := make(chan int, 3) coNum := 2 done := make(chan bool, coNum) for i := 1; i <= coNum; i++ { go Consumer(i, ch, done) } go Producer(ch) for i := 1; i <= coNum; i++ { <-done } }
运行结果:
$ ./chan2 id: 2, recv: 1 id: 1, recv: 2 id: 1, recv: 4 id: 1, recv: 5 id: 1, recv: 6 id: 2, recv: 3 id: 2, recv: 8 id: 2, recv: 9 id: 2, recv: 10 id: 2, closed id: 1, recv: 7 id: 1, closed
一个生产者,两个消费者。生产者生成20次,消费者各消费10次。
package main import "fmt" func Producer(ch chan int) { for i := 1; i <= 20; i++ { ch <- i } close(ch) } func Consumer(id int, ch chan int, done chan bool) { for i := 0; i < 10; i++ { fmt.Println(id, <-ch) } done <- true } func main() { ch := make(chan int) coNum := 2 done := make(chan bool, coNum) for i := 1; i <= coNum; i++ { go Consumer(i, ch, done) } go Producer(ch) for i := 1; i <= coNum; i++ { <-done } }