2011-11-22 103 views
1

是否有可能發生: 假設我有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://stackoverflow.com/questions/8232422/concurrent -outoutines-in-go) –

回答

2

我討厭抽象的例子,無論如何,我會盡我所能來回答你的問題。

是否有可能在例程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

0

這是不可能在GO中,我的意思是創建併發通道。

+1

你能否幫助我,爲什麼它不可能用於併發例程? – Arpssss