gpt4 book ai didi

go - Google 的 Go 语言中的并发例程

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

是否有可能:假设,我有 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 是否可以将这两个值和进一步处理(动态并发例程)?任何机构都可以帮助相应地修改此程序。

最佳答案

我讨厌抽象的例子,无论如何我会尽力回答你的问题。

Is it possible in go that routine 1 takes both two values and process it farther?

您想归档什么?在 routine1 中,您可以执行以下操作:

// Read exactly one command from routine2 as well as exactly
// one command from routine3
cmd1 := <-command12
cmd2 := <-command13
// Process the pair of the two commands here

// Process a single command only, which was either sent by routine2
// or by routine3. If there are commands available on both channels
// (command12 and command13) the select statement chooses a branch
// fairly.
select {
case cmd1 := <-command12:
// process command from routine 2
case cmd2 := <-command13
// process command from routine 3
}

我希望这能回答您的问题。另请注意,Go channel 默认支持多个作者(以及多个读者)。因此,每个 goroutine 只使用一个输入 channel 可能就足够了。例如,routine1 可能只从名为 command1 的 channel 读取命令,但 routine2 和 routine3 可能使用相同的 command1 channel 向 routine1 发送消息。

Go 中的另一个常见习惯用法是将回复 channel 作为消息的一部分传递。例如:

type Command struct {
Cmd string
Reply chan-> int
}

func routine2() {
reply := make(chan int)
command1 <- Command{"doSomething", reply}
status := <-reply
}

func routine1() {
cmd <- command1;
// process cmd.Cmd
cmd.Reply <- 200 // SUCCESS (status code)
}

根据您的实际问题,这可能会大大简化您的程序:)

关于go - Google 的 Go 语言中的并发例程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8234998/

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