multithreadinggoroutines

How to convert the following Thread statement in go


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


Solution

  • 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.