duankangpazhuo0347 2014-09-22 02:50
浏览 18
已采纳

第二通道导致死锁,即使独立

This is more a follow up question from this other post

I do not understand why adding a second channel (c2 in my case) will cause a deadlock. Channels are independent and I don't see why c2 is supposed to be blocked

Link to playground

func do_stuff(done chan bool) {
    fmt.Println("Doing stuff")
    done <- true
}

func main() {
    fmt.Println("Main")
    done := make(chan bool)
    go do_stuff(done)
    <-done
    //Up tp here everything works
    c2 := make(chan int)
    c2 <- 1
    fmt.Println("Exit ",<-c2)

}
  • 写回答

2条回答 默认 最新

  • dongshi8038 2014-09-22 02:57
    关注

    The statements

    c2 := make(chan int)
    c2 <- 1
    

    will always block. Link to Playground.

    Because the channel c2 is unbuffered, the send operation cannot proceed until another goroutine has received the value from the channel. There is no goroutine that can receive from the channel, therefore the send blocks forever.

    The channels section in Effective Go is a good place to read about unbuffered channels. Also see the sections on channels and send in the Go Language Specification.

    The program will work as I think you are expecting if you make c2 a buffered channel:

        c2 := make(chan int, 1)
    

    With this change, the send can proceed without synchronizing with a receiver.

    Link to Playground

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器