2014-01-11 6 views
8

誰かが説明することができます。チャンネルがバッファされると、プログラムはfatal_errorで終了しません。バッファされた/バッファされていないチャンネル

バッファなしチャネル

package main 

func main() { 
    c := make(chan int) 
    c <- 3 
} 

fatal error: all goroutines are asleep - deadlock! 

バッファチャンネル

package main 

func main() { 
    c := make(chan int, 1) 
    c <- 3 
} 

[no output] 

Program exited. 

ありがとうございます!

+0

私は思いますこれはバッファされたチャネルとバッファされていないチャネルの違いによるものです。バッファリングされたチャネルでは、送信側は受信側(この場合は受信側)がデータを取得するまで待機します。しかし、私は確信していません.. –

+2

[make(chan bool、1)とはどのように動作しますか?](http://stackoverflow.com/questions/20041392/how-does-makechan -bool-behave-differently-from-makechan-bool-1) – Matt

答えて

11

バッファ内に空きがある場合、バッファ付きチャネルへの書き込みはブロックされません。

使用すると、1つのバッファサイズとチャンネルに2つのアイテムを置くしようとした場合、あなたは同じエラーを取得:

package main 

func main() { 
    c := make(chan int, 1) 
    c <- 3 
    c <- 4 
} 

あなたが得られます。

fatal error: all goroutines are asleep - deadlock! 
1

おかげ@Matt

この記事の回答が見つかりましたHow does make(chan bool) behave differently from make(chan bool, 1)?

Actually that's the reason why your problem is generated. Un-buffered channels are only writable when there's someone blocking to read from it, which means you shall have some coroutines to work with -- instead of this single one.

2

これは、ブロックしているGoのチャネル(またはClojureのcore.asyncライブラリなどのその他のCSP実装)のコアコンセプトです。バッファがいっぱいになった場合には、ブロックバッファリング

  • :あなたはすでに述べたように一般的には、2種類のチャネルをそこにいます。
  • バッファされていない「ランデブー」がない場合はブロックされます。つまり、チャネルに()を追加する人物(c <-)が必要です。あなたの特定のケースで

のGoランタイムは、これまでのチャンネルcから3がかかります誰がないことを検出するのに十分スマートです。したがって、それはdeadlockであり、(ありがたいことに)エラーがスローされます。あなたはゴルーチンを使用しているチャンネルで作業しているときは、通常、産卵(チェックアウトthis introductionを)何

軽量スレッド管理の並行ゴーランタイム-する実行体によって:

c := make(chan int) 

go func() { c <- 3 }() // Create a new gorountine that puts 3 to the channel 

fmt.Println(<- c) // Take 3 from the channel and print it in the main thread 
関連する問題