deadlock
来源:3-6 RabbitMQ工作模式---Simple模式(下)
IT小书童z
2019-06-26
forever := make(chan bool)
//启用协程处理消息
go func() {
for d := range msgs {
//实现我们要处理的逻辑函数
log.Printf("Received a message: %s", d.Body)
}
}()
log.Printf("[*] Waiting for messages,To exit press CTRL")
<-forever
老师,这里只有收数据,没有发数据的地方,为什么不会deadlock
3回答
-
Cap
2019-07-01
这里有个坑要注意下,用rabbitmq的时候隐性的异步协程,这个携程一直运行,程序才不会出现死锁。
你这样写,表示所有协程都结束了,但是通过channel还在等待资源释放就导致了死锁,如果有任何一个协程没结束就不会有死锁。
10 -
Cap
2019-06-26
我们main函数本身是一个 goroutine,go func() { 启动了另一个信道,这里使用的是无缓冲信道。
从无缓冲信道取数据,必须要有数据流进来才可以,否则当前goroutine阻塞(main.go 等待结束);
132019-07-01 -
IT小书童z
提问者
2019-06-27
func main() { forever := make(chan bool) var msgs = "12123123123123" //log.Printf("[*] Waiting for messages,To exit press CTRL+c") go func() { for d := range msgs { //实现我们要处理的逻辑函数 log.Printf("Received a message: %d", d) } }() <-forever }
但是我单独拿出来,这样写,就会deadlock
2019/06/26 01:42:14 Received a message: 0
2019/06/26 01:42:14 Received a message: 1
2019/06/26 01:42:14 Received a message: 2
2019/06/26 01:42:14 Received a message: 3
2019/06/26 01:42:14 Received a message: 4
2019/06/26 01:42:14 Received a message: 5
2019/06/26 01:42:14 Received a message: 6
2019/06/26 01:42:14 Received a message: 7
2019/06/26 01:42:14 Received a message: 8
2019/06/26 01:42:14 Received a message: 9
2019/06/26 01:42:14 Received a message: 10
2019/06/26 01:42:14 Received a message: 11
2019/06/26 01:42:14 Received a message: 12
2019/06/26 01:42:14 Received a message: 13
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan receive]:
main.main()
D:/work/go/src/rabbitmqDemo/mainSimplePublish.go:20 +0x8b
Process finished with exit code 2
00