doudao8283 2013-10-27 02:11
浏览 166
已采纳

主范围结束时不调用goroutine的defer

package main

import(
    "fmt"
    "time"
)

func main(){
    fmt.Println("1")
    defer fmt.Println("-1")
    go func() { 
        fmt.Println("2")
        defer fmt.Println("-2")
        time.Sleep(9 * time.Second)
    }()
    time.Sleep(1 * time.Second)
    fmt.Println("3")
}

Produces the output: 1 2 3 -1 But I would've thought the goroutine's defer would have been called to produce: 1 2 3 -2 -1

In my actual code my goroutine is blocked on a websocket... I suppose I could send a shutdown signal but I haven't yet figured out how to do a wait-on-multiple-objects kind of thing (if it can actually be done in go). I'm currently solving my problem by hoisting the deferred -2 into the main scope.

Is there some trick to defer placement I'm not doing right?

http://play.golang.org/p/qv8UEuF2Rb

  • 写回答

4条回答 默认 最新

  • dream_life5200 2013-11-03 08:56
    关注

    (I don't have enough reps to comment?)

    Yes, the issue is with goroutine scheduling and is platform dependent. Use runtime.Gosched at the end of the function with the goroutine to ensure it gets some cputime. Presently on x86_64 linux, the code below will produce "3" but without Gosched it produces "1":

    No. That's not the issue, and that only solves it by co-incidence(via an implementation detail). As has already been hinted at in goroutine's defer not called when main scope ends . Your code is racy and you must therefore explicitly synchronize the goroutines. The simplest way is to to use a channel or a waitgroup http://golang.org/pkg/sync/#WaitGroup . Which option is more appropriate depends on what you're doing. If all you want to do is wait for some result, then have the gorutine send its result on the channel and you simply wait for it. If you just want to wait for a number of goroutines, then use a waitgroup.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?