我正在用Go编写程序,也使用Go频道编写了RMQ使用者,来到了这些场景。
“永远进入通道”阻塞主线程,直到它从其他go例程获取停止信号为止。
但是下面的程序1告诉死锁错误,并且程序2可以正常工作而没有死锁错误,为什么会发生?
程序1:进入例行打印元素,出现循环和死锁错误
package main
import "fmt"
func main() {
stopProgram := make(chan bool)
go func() {
for i := 0; i < 5; i++ {
fmt.Println("hello ",i)
}
// Send signal through stopProgram to stop loop
//stopProgram <- true
}()
// your problem will wait here until it get stop signal through channel
<-stopProgram
fmt.Println("after forever channel")
}
输出
hello 0
hello 1
hello 2
hello 3
hello 4
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan receive]:
main.main()
/home/main.go:26 +0x73
程序2:转到路由,以循环方式接收RMQ传递,并且没有死锁
package main
import (
"fmt"
)
func main() {
// assuming some code of registring exchange and queues with rabbitmq
msgs, err := ch.Consume(
q.Name, // queue
"", // consumer
true, // auto-ack
false, // exclusive
false, // no-local
false, // no-wait
nil, // args
)
stopProgram := make(chan bool)
go func() {
for d := range msgs {
fmt.Println("reveived message ",d.Body)
}
}()
// your problem will wait here until it get stop signal through channel
<-stopProgram
fmt.Println("after forever channel")
}
任何人都可以清除此处的频道(我是GO的新手)吗?
我的假设
-在程序1中,打印5次hello后,go路由结束,并且在当前例程/任何其他例程中没有无限执行,或者永远停止进入通道的停止信号。如果要永久使用go频道(或阻塞主Go例程以保留在特定的go例程中,则必须确保这些内容
无论哪个例程都可以确保无限执行,或者
Go例程将停止信号发送到永远的频道。
我正在用Go编写程序,并使用go频道编写RMQ使用者,来到了这些场景。 “永远进入通道”阻塞主线程,直到它从其他go例程获取停止信号为止。但下面...
当您的代码在一个没有人发送任何东西的通道上等待时,您会得到fatal error: all goroutines are asleep - deadlock!
。因此,在该通道上等待没有任何意义。