Go中的并发例程
我想写三个并发例程,它们相互发送整数。现在,我已经实现了两个并发例程,它们相互发送整数Go中的并发例程,go,concurrent-programming,Go,Concurrent Programming,我想写三个并发例程,它们相互发送整数。现在,我已经实现了两个并发例程,它们相互发送整数 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(
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)
}
主程序包
输入“兰特”
func Routine1(命令chan int,响应chan int){
对于i:=0;i<10;i++{
i:=兰特整数(100)
命令您尚未在main
函数中声明命令
和response
变量
func main() {
commands := make(chan int)
responses := make(chan int)
go Routine1(commands, responses, command, response)
Routine2(commands, responses)
Routine3(command, response)
}
正确。Go将command
和commands
视为不同的变量,并且您没有声明command
。Go语言中没有用于检测类似变量名并将其连接的功能。很抱歉,我犯了错误。但是,我更改了我的问题。另外一个问题是,是否可以创建双向链接有没有可能为int、string等创建一个公共通道?
func main() {
commands := make(chan int)
responses := make(chan int)
go Routine1(commands, responses, command, response)
Routine2(commands, responses)
Routine3(command, response)
}