1

我想编写三个并发例程,它们相互发送整数。现在,我已经实现了两个并发例程,它们相互发送整数。

package main
import "rand"

func Routine1(commands chan int, responses chan int) {
    for i := 0; i < 10; i++ {
        i := rand.Intn(100)
  commands <- i
  print(<-responses, " 1st\n");
}
close(commands)
}

func Routine2(commands chan int, responses chan int) {
for i := 0; i < 1000; i++ {
    x, open := <-commands
    if !open {
        return;
    }
     print(x , " 2nd\n");
    y := rand.Intn(100)
    responses <- y
}
}

func main() 
{
   commands := make(chan int)
   responses := make(chan int)
   go Routine1(commands, responses)
   Routine2(commands, responses)
}

但是,当我想添加另一个例程来向/从上述例程发送和接收整数时,它会给出诸如“抛出:所有 goroutines 都处于睡眠状态 - 死锁!”之类的错误。下面是我的代码:

package main
import "rand"

func Routine1(commands chan int, responses chan int, command chan int, response chan int ) {
for i := 0; i < 10; i++ {
    i := rand.Intn(100)
  commands <- i
  command <- i
  print(<-responses, " 12st\n");
  print(<-response, " 13st\n");
}
close(commands)
}

func Routine2(commands chan int, responses chan int) {
for i := 0; i < 1000; i++ {
    x, open := <-commands
    if !open {
        return;
    }
     print(x , " 2nd\n");
    y := rand.Intn(100)
    responses <- y
}
}

func Routine3(command chan int, response chan int) {
for i := 0; i < 1000; i++ {
    x, open := <-command
    if !open {
        return;
    }
     print(x , " 3nd\n");
    y := rand.Intn(100)
    response <- y
}
}

func main() {
   commands := make(chan int)
   responses := make(chan int)
   command := make(chan int)
   response := make(chan int)
   go Routine1(commands, responses,command, response )
   Routine2(commands, responses)
   Routine3(command, response)
}

任何人都可以帮助我,我的错误在哪里?任何人都可以帮助我,是否可以创建双向通道或者是否可以为 int、string 等创建一个公共通道?

4

1 回答 1

2

您尚未在函数中声明commandandresponse变量。main

func main() {
    commands := make(chan int)
    responses := make(chan int)
    go Routine1(commands, responses, command, response)
    Routine2(commands, responses)
    Routine3(command, response)
}
于 2011-11-22T19:25:14.893 回答