我想写三个并发例程,它们相互发送整数。现在,我已经实现了两个并发例程,它们相互发送整数。
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)
}
但是,当我想添加另一个想要向上述例程发送和接收整数的例程时,它会出现错误,例如&#34; throw:所有goroutines都睡着了 - 死锁!&#34;。以下是我的代码:
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等创建公共通道?
答案 0 :(得分:2)
您尚未在command
函数中声明response
和main
个变量。
func main() {
commands := make(chan int)
responses := make(chan int)
go Routine1(commands, responses, command, response)
Routine2(commands, responses)
Routine3(command, response)
}