2014-01-11 2 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

가능한 [(chan bool)은 make (chan bool, 1)과 어떻게 다르게 동작 하는가?] (http://stackoverflow.com/questions/20041392/how-does-makechan) -bool-behave-differently-from-makechan-bool-1) – Matt

답변

11

버퍼링 된 채널에 쓰기가 버퍼에 공간이 있으면 차단하지 않습니다.

하나의 버퍼 크기와 채널에 두 항목을 넣어하려고하면 같은 오류 얻을 :

fatal error: all goroutines are asleep - deadlock! 
1

감사합니다 @ 매트

을 :

package main 

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

당신에게 제공을

이 게시물에 대한 답변을 찾았습니다. 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 구현). 버퍼가 꽉 찬 경우 차단 버퍼

  • : 이미 언급 한 바와 같이 일반적으로, 채널의 두 가지 종류가있어.
  • 버퍼링되지 않은 채널에 "(렙델)"이 없으면 차단됩니다. 즉, (c <-)을 (를) 사람에게 보내고 다른 사람이 채널에서 (<- c)을 가져 오는 사람이어야합니다. 특정 경우

이동 런타임은 어느 채널 c에서 3를 취할 것입니다 아무도 없다 감지 할만큼 똑똑하다. 따라서 deadlock이고 (고맙게도) 오류가 발생합니다. 당신이 goroutines를 사용하는 채널로 작업 할 때 일반적으로 산란 (체크 아웃 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