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

问题描述 投票:-1回答:1

我试图在go中转换以下java语句的语句;

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();

我想知道,如何转换这个去?

谢谢

multithreading go routines
1个回答
6
投票

Golang使用了一个名为"goroutines"(灵感来自"coroutines")的概念,而不是许多其他语言使用的“线程”。

您的具体示例看起来像sync.WaitGroup类型的常见用法:

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.

请注意,示例中的SomeFunction(...)可以是任何类型的工作,并将与所有其他调用同时执行;但是,如果它本身使用goroutines那么它应该确保使用这里所示的类似机制,以防止从“SomeFunction”返回,直到它实际完成它的工作。

© www.soinside.com 2019 - 2024. All rights reserved.