标签:i++ lse int 生产者消费者 sum value produce 文件 rod
//生产者
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 consum %d value \n", id, value)
} else {
fmt.Printf("id : %d had closed \n", id)
break
}
}
done <- true
}
测试文件
const (
cur int = 2
)
func main() {
ch := make(chan int, 3)
done := make(chan bool, 1)
for i := 1; i <= 2; i++ {
go Consumer(i, ch, done)
}
go Producer(ch)
//注意这里,如果done channel里面没有true的化会一直阻塞直到有东西进来。
for i := 1; i <= cur; i++ {
<-done
}
}
标签:i++ lse int 生产者消费者 sum value produce 文件 rod
原文地址:https://www.cnblogs.com/jijiboy/p/11824514.html