douping6871 2018-08-01 20:53
浏览 33
已采纳

如何在go中转换以下Thread语句

I am trying to convert the following java statement of threads in go;

int num = 5;
    Thread[] threads = new Thread[5];
    for (int i = 0; i < num; i++)
    {
        threads[i] = new Thread(new NewClass(i));
        threads[i].start();
    }
    for (int i = 0; i < numT; i++)
        threads[i].join();

I wanted to know, how to convert this to go?

Thanks

  • 写回答

1条回答 默认 最新

  • dongxieyi9115 2018-08-01 21:02
    关注

    Golang uses a concept called "goroutines" (inspired by "coroutines") instead of "threads" used by many other languages.

    Your specific example looks like a common use for the sync.WaitGroup type:

    wg := sync.WaitGroup{}
    for i := 0; i < 5; i++ {      
        wg.Add(1) // Increment the number of routines to wait for.
        go func(x int) { // Start an anonymous function as a goroutine.
            defer wg.Done() // Mark this routine as complete when the function returns.
            SomeFunction(x)
        }(i) // Avoid capturing "i".
    }
    wg.Wait() // Wait for all routines to complete.
    

    Note that SomeFunction(...) in the example can be work of any sort and will be executed concurrently with all other invocations; however, if it uses goroutines itself then it should be sure to use a similar mechanism as shown here to prevent from returning from the "SomeFunction" until it is actually done with its work.

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

报告相同问题?

悬赏问题

  • ¥15 chaquopy python 安卓
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 CSS实现渐隐虚线框
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容