dpqvwgr74759 2017-08-21 18:17
浏览 52


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)

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




  • ¥20 python 3des pyDes库
  • ¥15 关于#mysql#安装失败的问题。MySQL
  • ¥15 想问一下for循环计算表达式的方法,第一次接触
  • ¥15 如何在VA框架上面加功能,去读取框架内任何app数据功能
  • ¥15 关于#c语言#的问题:用c或c++写一个计算下列问题有关软件工程的代码并加上分析
  • ¥15 Zeppelin0.10.0版本升级lib包下的shiro-web
  • ¥15 链表入队的指针内存问题
  • ¥20 vba如何写本地html文件执行js
  • ¥15 VS2022的C#如何创建
  • ¥20 关于#用户注册#的问题,如何解决?