dongxin0031 2014-04-30 04:53
浏览 128
已采纳

Golang goroutine无法使用在通道上使用范围的功能运行defer

A range on a channel

for s := range cs {
    fmt.Println("Recieved Cake: ", s)
}

should keep a function open until the channel closes at which point the function/goroutine should terminate. When a function terminates the defer function should run just prior. This doesn't seem to be the case and I can't find any reasons why.

Sample code at http://play.golang.org/p/ADu1MzAe9P produces defer statements as expected except for the function that is recieving from the channel. Any reasons as to why this would be? thanks!

  • 写回答

1条回答 默认 最新

  • drix47193 2014-04-30 05:03
    关注

    The reason why the defer function is not executing is that the application reaches the end of the main function causing the entire program to terminate without waiting for goroutines.

    Go Specification says:

    When the function main returns, the program exits. It does not wait for other (non-main) goroutines to complete.

    Since your recieveCakeAndPack is still waiting for the channel to close (which never happens) it will never defer before the termination of the program.

    Edit

    On a side note - putting the defer statements last in a function is not meaningful. Instead put them directly after the statement you want to defer such as:

    fmt.Println("Entering function")
    defer fmt.Println("Leaving function")
    

    or

    file, err := os.Open("file.txt")
    if err != nil {
        return err
    }
    defer file.Close()
    

    The defer function/method calls will be executed when leaving the function in a Last-In-First-Out order.

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

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测