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 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)