What will happen if i do not add waitgroup in go routine?

huangapple go评论66阅读模式
英文:

What will happen if i do not add waitgroup in go routine?

问题

在Golang服务器(使用echo框架)中的一个端点中,我正在使用go routine触发一些函数,但我没有向该go routine添加任何waitgroup。

server.router.PATCH(path.Join(server.Config.APIPath, "/dummy"), h.SomeFunc)

// /dummy
func (h * )SomeFunc() error {
    go func() {
        someTask()
    }
}

每个地方都建议我应该像这样编写:

func (h * )SomeFunc() error {
    var wg sync.WaitGroup
    wg.Add(1)
    go func() {
        someTask()
        wg.Done()
    }
    wg.Wait()
}

如果我没有按照建议添加waitgroup,会发生什么?会导致内存泄漏吗?

英文:

In the Golang server(using echo framework) in one of the endpoint i am triggering some function using go routine, but i am not adding any waitgroup to that go routine.

server.router.PATCH(path.Join(server.Config.APIPath, "/dummy"), h.SomeFunc)

// /dummy
func (h * )SomeFunc() error {
go func() {
someTask()
}
}

every where it suggests i should have written like

func (h * )SomeFunc() error {
var wg.syncWaitGroup
wg.Add(1)
go func() {
someTask()
wg.done()
}
wg.wait()
}

What will happen if i did not add waitgroups as suggested ? is it going to cause memory leak ?

答案1

得分: 1

这不会导致内存泄漏。然而,很可能goroutine在函数返回之前不会完成,导致请求处理完成。如果需要goroutine的结果来构建响应给客户端,那么客户端将会收到空的或不完整的响应。WaitGroup确保在SomeFunc返回之前goroutine完成。

然而,如果处理程序用于启动一些在处理程序返回后将继续运行的异步进程,那么应该使用不带有WaitGroup的版本。

英文:

It will not cause a memory leak. However, it is likely that the goroutine will not finish until the function returns, causing the request handling to complete. If the result of the goroutine is required to build the response to the client, that means the client will get empty or incomplete response. The waitgroup ensures that the goroutine completes before the SomeFunc returns.

If however, the handler is used to start some asynchronous process that will continue running after the handler returns, you should use the version without the WaitGroup.

huangapple
  • 本文由 发表于 2021年8月30日 21:30:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/68985012.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定