如果直接在main方法中读取会出现error,如果使用go receive方式程序正常

does · 2019-02-17 22:02:51 · 993 次点击

这个代码一共创建了11个goroutine, send 10个, main 1个, 当send 10 个都运行完后, 唯一一个main goroutine就阻塞在接受通道的for循环那等待数据进来, 此时没有任何goroutine可以运行, 所以发生死锁

#6
更多评论

因为如果放在main中,会从channel中读数据,没有读到就会死锁。

#1

@waini1110</a>

首先感谢回答,另外:

对于读取来说应该是发现channel有数据就拿 ,没有数据就阻塞
对于发送来说向channel中存,存完阻塞,等待channel数据被取走后再存
现在我在main中不断读取channel, 假设channel不存在数据,他应该只是阻塞状态,为什么会提示 all goroutines are asleep - deadlock
#2