【问题标题】:Concurrent routines in GoGo 中的并发例程
【发布时间】:2012-01-04 04:02:40
【问题描述】:

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

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 等创建一个公共通道?

【问题讨论】:

    标签: go concurrent-programming


    【解决方案1】:

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

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

    【讨论】:

    • 正确。 Go 将 commandcommands 视为不同的变量,而您没有声明 command。 Go 语言中没有检测相似变量名并连接它们的功能。
    • 对不起,我的错误。但是,我改变了我的问题。还有一个问题是可以创建双向通道吗?是否可以为 int、string 等创建一个公共通道?
    猜你喜欢
    • 1970-01-01
    • 2012-01-11
    • 2018-01-02
    • 1970-01-01
    • 2012-01-11
    • 2018-02-18
    • 2019-05-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多