나는 3 개의 goroutine 체인을 설정하고 있는데, 각 입력에는 출력 채널이 있습니다. goroutine은 입력 채널을 닫을 때까지 읽습니다. 값을 증가시키고 출력 채널로 보냅니다. 그러나,이 출력 교착 아래 프로그램 :이 Go 프로그램이 중단되는 이유는 무엇입니까?
goroutine 'one': 1
goroutine 'two': 2
goroutine 'three': 3
goroutine 'one': 10
goroutine 'two': 11
goroutine 'one': 100
fatal error: all goroutines are asleep - deadlock!
코드 : 출력 채널에서 읽고 루프에 도달하지 않기 때문에
package main
import (
"fmt"
)
func int_channel(id string, i chan int, o chan int) {
defer close(o)
for x := range i {
fmt.Printf("goroutine '%s': %d\n", id, x)
o <- x + 1
}
fmt.Println("done")
}
func main() {
c0 := make(chan int)
c1 := make(chan int)
c2 := make(chan int)
c3 := make(chan int)
go int_channel("one", c0, c1)
go int_channel("two", c1, c2)
go int_channel("three", c2, c3)
c0 <- 1
c0 <- 10
c0 <- 100
c0 <- 1000
c0 <- 10000
c0 <- 100000
close(c0)
fmt.Println("Sent all numbers to c0")
for x := range c3 {
fmt.Printf("out: %d\n", x)
}
}
이제는 분명해 보인다. :) Go 동시성 모델에 여전히 익숙해지고있다. 감사! –
또 다른 대안은'c0'을 버퍼링 된 채널로 만들고, 모든 초기 "데이터 충만 (stuffing of data)"을 수용 할 수있는 충분한 용량을 갖도록하는 것입니다. – Vatine