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.

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

报告相同问题?