Google Go语言中的并发例程

问题描述:

是否有可能发生: 假设我有3个并发例程可以将整数发送给对方。现在,假设两个并发例程都向并发例程1发送一个整数。例程1是否可能取得两个值并将其处理得更远?要清楚,我有以下代码:Google Go语言中的并发例程

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可以发送一个int常规2或3。我想这是例行3.现在假设,常规3还发送一个int到例程2.例程2是否有可能采用这两个值并进一步处理(动态并发例程)?任何机构都可以帮助相应地修改这个程序。

+0

可能重复(http://*.com/questions/8232422/concurrent -outoutines-in-go) –

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

是否有可能在例程1中同时采用两个值并将其处理得更远?

你想存档什​​么?里面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 

OR

// 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频道默认支持多个作者(以及多读者)。因此,每个goroutine只需使用一个输入通道即可。例如,例程1可能只能从名为command1的通道读取命令,但例程2和例程3都可能使用相同的command1通道将消息发送到例程1。

Go的另一个常见习惯是将回复通道作为消息的一部分。例如:

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

根据您的实际问题,这可能会简化程序大大:) [围棋并发程序]的

+0

谢谢tux21b ..这比我真正想要的更好..非常感谢.. – Arpssss

这是不可能在GO中,我的意思是创建并发通道。

+1

你能否帮助我,为什么它不可能用于并发例程? – Arpssss