douchen2595 2015-07-27 15:28
浏览 346

goroutine的Return与Goexit对比

I did some digging, but didn't really find anything satisfactory, so I'm asking: are their any best practices or pros/cons for using return vs. runtime.Goexit for exiting a goroutine? So far, the only thing I came across in some testing is that if you're using waitgroups, it may not call the Done function.

Specific to the waitgroups (if interested): in some quick testing in a codebase I have, I create an anonymous function that executes as a goroutine to test a method that's supposed to run within a goroutine. I tried to use defer to have it call wg.Done() when the function called runtime.Goexit, but it didn't work. Not sure if this is intended or a bug.

Code example:

go func() {
    wg.Add(1)
    defer wg.Done()
    // Function goes here...
}()
  • 写回答

1条回答 默认 最新

  • dongwei2030 2015-07-27 15:31
    关注

    You should rarely ever need to use runtime.Goexit. It's used to terminate the current goroutine, when you can't return from the call site, e.g. when you are in a function call within the goroutine. In the std library, the testing package uses it in functions like FailNow and SkipNow to immediately end the current test. In general, you should return normally from your goroutines to keep the code clear, and prevent unexpected behavior.

    The problem in your example is that you need to call wg.Add before you start the goroutine, otherwise you could reach the Wait call before the wg.Add calls have been executed.

    wg.Add(1)
    go func() {
        defer wg.Done()
        // Function goes here...
    }()
    
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?