dswqw66280 2017-04-09 05:34
浏览 7
已采纳

选择准时。结果僵持后

package main

import "time"

func main() {
    chan_never_used := make(chan int, 10)

    c := make(chan int, 10)
    for {
        select {
        case <-time.After(time.Second):
            c <- 0
        case c <- <-chan_never_used:
        }

        println(<-c)
    }
}

https://play.golang.org/p/7hZMdITecg

The code above results in fatal error: all goroutines are asleep - deadlock!.

But if I change one line:

package main

import "time"

func main() {
    chan_never_used := make(chan int, 10)

    c := make(chan int, 10)
    for {
        select {
        case <-time.After(time.Second):
            c <- 0
        case n := <-chan_never_used: // This line changed
            c <- n                   // Add this line
        }

        println(<-c)
    }
}

It works well.

Why the first version of code results in deadlock and why could this change make the code work?

  • 写回答

1条回答 默认 最新

  • douren2395 2017-04-09 07:51
    关注

    As per the standard the select statement contains of a bunch of Send or Receive statements.

    In this case it is the send statement.

    Send statement is defined as:

    SendStmt = Channel "<-" Expression .
    Channel  = Expression .
    

    Looking at your code:

    case c <- <-chan_never_used:
    

    The Channel fraction is c, the Expression fraction is <-chan_never_used.

    So, the select semantics of the Send Statement of being (potentially) non-blocking is not applicable because it is the expression that blocks. And before the Send Statements semantics is applied the Expression part must be completely evaluated.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题