运行结果
Multirun start
task id 0 , timeout
task id 1 , timeout
task id 2 , sleep 1 second
Multissh finished. Process time 5s. Number of task is 3
Program exited.
chLimit 的缓冲是 1。task 0 和 task 1 耗时 2 秒超时。task 2 耗时 1 秒。总耗时 5 秒。并发限制生效了。
如果我们修改并发限制为 2
chLimit := make(chan bool, 2)
运行结果
Multirun start
task id 0 , timeout
task id 1 , timeout
task id 2 , sleep 1 second
Multissh finished. Process time 3s. Number of task is 3
Program exited.
task 0 , task 1 并发执行,耗时 2秒。task 2 耗时 1秒。总耗时 3 秒。符合预期。
有没有注意到代码里有个地方和之前不同。这里,用了一个带缓冲的 channel
chs[i] = make(chan string, 1)
还记得上面的例子么。如果 channel 不带缓冲,那么直到他被消费掉之前,这个 goroutine 都会被阻塞挂起。
然而如果这里的并发限制,也就是 chLimit 生效阻塞了主 goroutine,那么后面消费这些数据的代码并不会执行到。。。于是就 deadlock 拉!
for _, ch := range chs {
fmt.Println(<-ch)
}
所以给他一个缓冲就好了。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易采站长站。









