2011-11-22 21 views
1

我想編寫三個併發例程來互相發送整數。現在,我已經實現了兩個發送整數的併發例程。Go中的併發例程

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

然而,當我要新增想要從上面的程序發送和接收整數/另一個例程,它給像「扔!:所有夠程都睡着了 - 死鎖」的錯誤。以下是我的代碼:

package main 
import "rand" 

func Routine1(commands chan int, responses chan int, command chan int, response chan int) { 
for i := 0; i < 10; i++ { 
    i := rand.Intn(100) 
    commands <- i 
    command <- i 
    print(<-responses, " 12st\n"); 
    print(<-response, " 13st\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 Routine3(command chan int, response chan int) { 
for i := 0; i < 1000; i++ { 
    x, open := <-command 
    if !open { 
     return; 
    } 
    print(x , " 3nd\n"); 
    y := rand.Intn(100) 
    response <- y 
} 
} 

func main() { 
    commands := make(chan int) 
    responses := make(chan int) 
    command := make(chan int) 
    response := make(chan int) 
    go Routine1(commands, responses,command, response) 
    Routine2(commands, responses) 
    Routine3(command, response) 
} 

任何人都可以幫助我,我的錯誤在哪裏?任何人都可以幫助我,是否可以創建雙向通道或者是否可以爲int,string等創建公共通道?

回答

2

您還沒有在main函數中聲明commandresponse變量。

func main() { 
    commands := make(chan int) 
    responses := make(chan int) 
    go Routine1(commands, responses, command, response) 
    Routine2(commands, responses) 
    Routine3(command, response) 
} 
+1

正確。 Go將'command'和'commands'視爲不同的變量,並且你沒有聲明'command'。 Go語言沒有檢測類似變量名稱並連接它們的功能。 –

+0

對不起,我的錯誤。但是,我改變了我的問題。另外一個問題是可以創建雙向渠道嗎?是否有可能爲int,string等創建一個公共通道? – Arpssss