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 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘