频道发送到哪里有什么问题

  • 本文关键字:问题 频道 go channel
  • 更新时间 :
  • 英文 :


此程序输出:

fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan send]:
main.main()
/home/user/go/src/examples/run/chan1.go:51 +0xa9

但是注释第5行c <- 1和取消注释第9行//c <- 1(或者第8行-好的,这是有意义的(没有问题。这对管理通道有意义吗

func main() {
c := make(chan int)
q := make(chan int)
w := make(chan int)
c <- 1
go func() { q <- <-c}()
go func() { w <- <-q}()
// go func() {c <- 1}()
//c <- 1
fmt.Println(<-w)
}

我已经注释掉了代码的相关部分,这样就可以理解了。

package main
import "fmt"
func main() {
c := make(chan int) // unbuffered channel
q := make(chan int) // unbuffered channel
w := make(chan int) // unbuffered channel
// As c, q and w are unbuffered: so for a send to happen,
// receiver must be ready or eventually ready. If somehow the
// receiver can't be ready, then it's a deadlock because send
// cannot happen.
//
// Example:
// c := make(chan int)
//
// c <- 1   // send
// <-c      // receive
//
// In the above example the send cannot happen as c <- 1
// is a synchronous call i.e., it cannot proceed to next instruction
// unless c <- 1 gets executed. And condition for the send to happen
// is that their should be a receiver i.e., <-c
// Hence, a deadlock
// Spawn a goroutine so that c is ready
// Non-blocking i.e., program can proceed to next instruction
// even if q <- <-c is not executed.
go func() {
q <- <-c
}()
// Spawn a goroutine so that q is ready
// Non-blocking i.e., program can proceed to next instruction
// even if w <- <-q is not executed.
go func() {
w <- <-q
}()
// So, c is ready or eventually ready as it's handled by a already
// spawned goroutine.
c <- 100
// c -> q -> w
// There value sent to c will reach w
fmt.Println(<-w)
}

最新更新