我想编写三个并发的 go 例程,它们相互发送整数。现在,我的代码已正确编译,但是在第一次执行后,它给出了错误“所有 goroutines 都在睡觉 - 死锁!”。我试图找到错误,但我无法在代码逻辑中找到任何错误。任何人都可以帮助我找到我的代码中的错误。我的代码如下。提前致谢。
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)
}
谁能告诉我为什么如果我将 Routine2 和 Routine3 声明为 goroutine,为什么输出是 [无输出]。我是 GO 的新手,据我从“ http://golang.org/doc/effective_go.html#concurrency ”了解,go 用于在同一地址空间中与其他 goroutine 并行执行 goroutine。那么,问题是什么,所有例程都在运行但输出是[无输出]。
为了使程序更清晰:实际上我很累做的是在每两个例程之间创建两个通道,然后使用一个通道将 int 发送到另一个通道并通过另一个通道从该例程接收 int。例如,例程 1 和 3 之间的通道是命令 13 和响应 13。例程 1 使用 command13 向例程 3 发送 int 和 response13 来接收 int。对于例程 3,response13 用于向例程 1 发送 int,而 command13 用于从例程 1 接收 int(命令/响应 13 代表例程 1 和 3 之间的通道)。现在,由于三个例程是并发的,并且它们具有特定的例程来处理接收到的 msg 或发送 msg,为什么它们会陷入死锁?