1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| func main() { maxNum := 3 limit := make(chan bool, maxNum) //缓存通道 quit := make(chan bool) //无缓存通道
for i := 0; i < 9; i++ { limit <- true //缓存满3个 产生阻塞 执行下方的 gororutine fmt.Println("start worker : ", i) go func(i int) { //执行这个gororutine 从代码上看这个gororutine不会阻塞 //保持这个gororutine 不会阻塞 fmt.Println("do worker start: ", i) time.Sleep(time.Millisecond * 200) fmt.Println("do worker finish: ", i) res := <- limit // 取出一个chan limit缓存剩余2个,缓存通道开启,继续执行上面的 for 然后会在次阻塞,但是这个里面会继续执行 fmt.Println(res) if i == 8 { quit <- true //存入值 主程序获取到这个值 关闭主程序阻塞 fmt.Println("主程序退出") }
}(i) }
<-quit //chan读取数据一直读取不到 开启主程序阻塞 fmt.Println("收到退出通知,主程序退出") }
|