Go中的并发例程



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

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, " 1stn");
}
close(commands)
}
func Routine2(commands chan int, responses chan int) {
for i := 0; i < 1000; i++ {
    x, open := <-commands
    if !open {
        return;
    }
     print(x , " 2ndn");
    y := rand.Intn(100)
    responses <- y
}
}
func main() 
{
   commands := make(chan int)
   responses := make(chan int)
   go Routine1(commands, responses)
   Routine2(commands, responses)
}

然而,当我想要添加另一个想要向上述例程发送和接收整数的例程时,它会给出类似"throw: all gooutines are asleep - deadlock!"的错误。下面是我的代码:

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, " 12stn");
  print(<-response, " 13stn");
}
close(commands)
}
func Routine2(commands chan int, responses chan int) {
for i := 0; i < 1000; i++ {
    x, open := <-commands
    if !open {
        return;
    }
     print(x , " 2ndn");
    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 , " 3ndn");
    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等创建一个公共通道?

您没有在main函数中声明commandresponse变量。

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

相关内容

  • 没有找到相关文章

最新更新