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 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办