gpt4 book ai didi

go - Go 中的并发例程

转载 作者:IT王子 更新时间:2023-10-29 02:06:29 24 4
gpt4 key购买 nike

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

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)
}

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

最佳答案

您还没有在 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 - Go 中的并发例程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8232422/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com