相互に整数を送信する 3 つの同時進行の 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++ {
y := rand.Intn(10)
if y%2 == 0 {
command12 <- y
}
if y%2 != 0 {
command13 <- y
}
select {
case cmd1 := <-response12:
print(cmd1, " 1st\n")
case cmd2 := <-response13:
print(cmd2, " 1st\n")
}
}
close(command12)
}
func Routine2(command12 chan int, response12 chan int, command23 chan int, response23 chan int) {
for i := 0; i < 10; i++ {
select {
case x, open := <-command12:
{
if !open {
return
}
print(x, " 2nd\n")
}
case x, open := <-response23:
{
if !open {
return
}
print(x, " 2nd\n")
}
}
y := rand.Intn(10)
if y%2 == 0 {
response12 <- y
}
if y%2 != 0 {
command23 <- y
}
}
}
func Routine3(command13 chan int, response13 chan int, command23 chan int, response23 chan int) {
for i := 0; i < 10; i++ {
select {
case x, open := <-command13:
{
if !open {
return
}
print(x, " 2nd\n")
}
case x, open := <-command23:
{
if !open {
return
}
print(x, " 2nd\n")
}
}
y := rand.Intn(10)
if y%2 == 0 {
response13 <- y
}
if y%2 != 0 {
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)
go Routine2(command12, response12, command23, response23)
Routine3(command13, response13, command23, response23)
}
Routine2 と Routine3 を go ルーチンとして宣言すると、なぜ出力が [出力なし] になるのか、誰か教えてください。私は GO が初めてで、「http://golang.org/doc/effective_go.html#concurrency」から理解したように、go は同じアドレス空間で他のゴルーチンと並行してゴルーチンを実行するために使用されます。では、すべてのルーチンが実行されているのに、出力が [出力なし] であるという問題は何ですか。
プログラムをより明確にするために:実際に私がするのは、2つのルーチンごとに2つのチャネルを作成し、1つのチャネルを使用してintを他のチャネルに送信し、そのルーチンから別のチャネルでintを受信することです。たとえば、ルーチン 1 と 3 の間のチャネルは command13 と response13 です。ルーチン 1 は、command13 を使用して int を送信し、response13 を使用してルーチン 3 との間で int を受信します。さて、3 つのルーチンが並行しており、受信メッセージまたは送信メッセージを処理する特定のルーチンがあるのに、なぜデッドロックに陥るのでしょうか?