-1

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

Sucheta
  • 11
  • 7
  • Java is a very different language than Go. "Converting" Java to Go is unlikely to yield good results. Rather, try to take your goals and requirements and reimplement them in Go using Go idioms. – Adrian Aug 02 '18 at 12:12

1 Answers1

5

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.

maerics
  • 151,642
  • 46
  • 269
  • 291
  • I have a qs.. https://play.golang.org I am trying to execute this.. the value for test-I is always 10. I wanted it to be that of value of i, which I am passing to the test(). I wanted to know, why its just taking 10? – Sucheta Aug 08 '18 at 01:25
  • @Sucheta sounds like a separate question to me – maerics Aug 08 '18 at 02:46