我想编写三个并发的 go 例程,相互发送整数。现在,我的代码已正确编译,但是在第一次执行后,它给出错误“所有 goroutine 都在睡觉 - 死锁!”。我试图找到错误,但无法找到代码逻辑中的任何错误。任何人都可以帮助我找到代码中的错误吗?我的代码如下。提前致谢。
package main
import "rand"
func Routine1(command12 chan int, response12 chan int, command13 chan int, response13 chan int) {
for i := 0; i < 10; i++ {
y := rand.Intn(10)
if y%2 == 0 {
command12 <- y
}
if y%2 != 0 {
command13 <- y
}
select {
case cmd1 := <-response12:
print(cmd1, " 1st\n")
case cmd2 := <-response13:
print(cmd2, " 1st\n")
}
}
close(command12)
}
func Routine2(command12 chan int, response12 chan int, command23 chan int, response23 chan int) {
for i := 0; i < 10; i++ {
select {
case x, open := <-command12:
{
if !open {
return
}
print(x, " 2nd\n")
}
case x, open := <-response23:
{
if !open {
return
}
print(x, " 2nd\n")
}
}
y := rand.Intn(10)
if y%2 == 0 {
response12 <- y
}
if y%2 != 0 {
command23 <- y
}
}
}
func Routine3(command13 chan int, response13 chan int, command23 chan int, response23 chan int) {
for i := 0; i < 10; i++ {
select {
case x, open := <-command13:
{
if !open {
return
}
print(x, " 2nd\n")
}
case x, open := <-command23:
{
if !open {
return
}
print(x, " 2nd\n")
}
}
y := rand.Intn(10)
if y%2 == 0 {
response13 <- y
}
if y%2 != 0 {
response23 <- y
}
}
}
func main() {
command12 := make(chan int)
response12 := make(chan int)
command13 := make(chan int)
response13 := make(chan int)
command23 := make(chan int)
response23 := make(chan int)
go Routine1(command12, response12, command13, response13)
go Routine2(command12, response12, command23, response23)
Routine3(command13, response13, command23, response23)
}
谁能告诉我为什么如果我将例程和例程3声明为goroutine,为什么输出是[无输出]。我是 GO 新手,据我了解,“http://golang.org/doc/ effective_go.html#concurrency http://golang.org/doc/effective_go.html#concurrency”,go 用于与同一地址空间中的其他 goroutine 并行执行 goroutine。那么,问题是什么,所有例程都在运行,但输出是[无输出]。
为了使程序更清晰:实际上我很累的是在每两个例程之间创建两个通道,然后使用一个通道将 int 发送到另一个通道,并通过另一个通道从该例程接收 int。例如,例程 1 和 3 之间的通道是命令 13 和响应 13。例程 1 使用 command13 发送 int,使用 response13 从例程 3 接收 int。对于例程 3,response13 用于向例程 1 发送 int,使用 command13 从例程 1 接收 int(命令/响应 13 代表例程 1 和例程 3 之间的通道)。现在,由于三个例程是并发的,并且它们有特定的例程来处理接收的消息或发送消息,为什么它们会陷入死锁?