是否有可能:假设,我有 3 个并发例程可以相互发送整数。现在,假设并发例程 2 和 3 都向并发例程 1 发送一个整数。例程 1 是否有可能同时获取两个值并进一步处理它?为了清楚起见,我有以下代码:
package main
import "rand"
func Routine1(command12 chan int, response12 chan int, command13 chan int, response13 chan int ) {
for i := 0; i < 10; i++ {
i := rand.Intn(100)
if i%2 == 0 {
command12 <- i
}
if i%2 != 0 {
command13 <- i
}
print(<-response13, " 1st\n");
}
close(command12)
}
func Routine2(command12 chan int, response12 chan int, command23 chan int, response23 chan int) {
for i := 0; ; i++ {
x, open := <-command12
if !open {
return;
}
print(x , " 2nd\n");
y := rand.Intn(100)
if i%2 == 0 {
command12 <- y
}
if i%2 != 0 {
command23 <- y
}
}
}
func Routine3(command13 chan int, response13 chan int, command23 chan int, response23 chan int) {
for i := 0; ; i++ {
x, open := <-command13
if !open {
return;
}
print(x , " 3nd\n");
y := rand.Intn(100)
response23 <- y
}
}
func main() {
command12 := make(chan int)
response12 := make(chan int)
command13 := make(chan int)
response13 := make(chan int)
command23 := make(chan int)
response23 := make(chan int)
go Routine1(command12, response12,command13, response13 )
Routine2(command12, response12,command23, response23)
Routine3(command13, response13,command23, response23 )
}
在这里,在这个例子中,例程 1 可以向例程 2 或 3 发送一个 int。我假设它是例程 3。现在假设例程 3 也向例程 2 发送一个 int。例程 2 是否可以采用这两个值并处理进一步(动态并发例程)?任何机构都可以帮助相应地修改这个程序。