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

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条回答 默认 最新

相关推荐 更多相似问题