dpqvwgr74759
2017-08-21 18:17
浏览 51
已采纳

Golang:WaitGroup是否可以使用Go例程泄漏

I am planning to implement a go-routine and have a sync.WaitGroup to synchronize end of a created go-routine. I create a thread essentially using go <function>. So it is something like:

main() {
    var wg sync.WaitGroup
    for <some condition> {
        go myThread(wg)
        wg.Add(1)
    }
    wg.wait()
}

myThread(wg sync.WaitGroup) {
    defer wg.Done()
}

I have earlier worked with pthread_create which does fail to create a thread under some circumstances. With that context, is it possibly for the above go myThread(wg) to fail to start, and/or run wg.Done() if the rest of the routine behaves correctly? If so, what would be reported and how would the error be caught? My concern is a possible leak in wg due to wg.Add(1) following the thread creation. (Of course it may be possible to use wg.Add(1) within the function, but that leads to other races between the increment and the main program waiting).

I have read through numerous documentation of go-routines and there is no mention of a failure in scheduling or thread creation anywhere. What would be the case if I create billions of threads and exhaust bookkeeping space? Would the go-routine still work and threads still be created?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongshi1207 2017-08-21 18:22
    已采纳

    I don't know of any possible way for this to fail, and if it is possible, it would result in a panic (and therefor application crash). I have never seen it happen, and I'm aware of examples of applications running millions of goroutines. The only limiting factor is available memory to allocate the goroutine stack.

    go foo() is not like pthread_create. Goroutines are lightweight green threads handled by the Go runtime, and scheduled to run on OS threads. Starting a goroutine does not start a new OS thread.

    点赞 评论
  • douyou7102 2017-08-22 05:47

    The problem with your code is not in starting a goroutine (which cannot "fail" per se) or that like but in the use of sync.WaitGroup. Your code has two major bugs:

    1. You must do wg.Add(1) before launching the goroutine as otherwise the Done() could be executed before the Add(1).

    2. You must not copy a sync.WaitGroup. Your code makes a copy while calling myThread().

    Both issues are explained in the official documentation to sync.WaitGroup and the given example in https://golang.org/pkg/sync/#WaitGroup

    点赞 评论