dsfs21312 2018-11-26 13:46
浏览 106
已采纳

与goroutine并行运行代码的首选语法是什么?

Let's say I need to call a function twice. The usual way to do it would be:

func main() {
    var wg sync.WaitGroup
    wg.Add(2)

    go func() {
        doSomething(A)          
        wg.Done()
    }()

    go func() {
        doSomething(B)
        wg.Done()
    }()
    wg.Wait()
}

But what about writing it like this ?

func main() {
    var wg sync.WaitGroup
    wg.Add(2)

    go func() {
        doSomething(A)          
        wg.Done()
    }()

    doSomething(B)
    wg.Done()
    wg.Wait()
}

We spare ourselves the creation of one goroutines, while making use of the main goroutine. But I've never seen it written like that in any tutorial. Is it wrong to do this? I've done tests and the output are just as I though the same.

  • 写回答

1条回答 默认 最新

  • dongsigan2636 2018-11-26 13:50
    关注

    Both are correct. The first form is cleaner and scales well if you intend to extend your code later, e.g. if you later decide you want to launch not 2 but 3 or 4 or N goroutines, the code will not change in structure, you just add the additional goroutines.

    Another reason why the first form is "popular" is because often after launching the "worker" goroutines there are more things to do which may be executed on this goroutine (before wg.Done() is called).

    The 2nd form on the other hand is more efficient, as it only launches one additional goroutine. Goroutines are lightweight, cheap, but they are not "free". This may be improved further by using the WaitGroup to only "track" the launched goroutine, obviously the "main" that calls wg.Wait() does not need to wait for itself explicitly. And if only 1 goroutine remains, you may use other synchronization means instead of WaitGroup (e.g. a channel).

    So basically if performance is critial, use the 2nd approach.

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

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料