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 51寻迹小车定点寻迹
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题
  • ¥15 Utunbu中vscode下cern root工作台中写的程序root的头文件无法包含
  • ¥15 麒麟V10桌面版SP1如何配置bonding
  • ¥15 Marscode IDE 如何预览新建的 HTML 文件