One Thread For Each For Loop

Hello mates, I am trying to implement two for loops that run in one thread each. My background is in c++ (image processing). In c++ I can start a thread for each for loop, therefore each for, inside the same main function, concurs with the other one. Below the summarized code:


import (
	"fmt"
	"os"
	"sync"

	"github.com/antonel/owe-sdk-go/v1"
	"github.com/joho/godotenv"
)

func main() {

	//I would like to start the thread 1 here
	for i := 0; i < 1000; i++ {

		Work(node 1/port8080)
	
	}

    //Start the second thread here 
    for i := 0; i < 1000; i++ {

		Work(node 2/port7070)
		
	}


}

I found the examples about WaitGroup/go func, but it looks like work only inside the loop not for different for loops, for least it is what I understood. Please I need some help.

1 Like

You need to wrap each loop into a go-routine and then use a WaitGroup to eventually join your three go routines again.

Roughly and pseudo codish as I am on a mobile:

func main() {
    wg = new(WaitGroup)
    wg.Add(2)
    
    go func(innerWG WaitGroup) {
        for ... { ... }
        innerWG.Done()
    }(wg)

    go func(innerWG WaitGroup) {
        for ... { ... }
        innerWG.Done()
    }(wg)

    wg.Wait()
}
3 Likes

Just a quick note that a goroutine isn’t necessarily a thread:

I’m pretty sure you meant “goroutine” and not “thread” but figured it was worth noting.

3 Likes

Thank you! I wanted to mention that, though it seems to have slipped through after I spend so many days writing that snippet on the phone :smiley:

2 Likes

Thank you for write this through your smartphone! :smile:

Yes, I read this article (thank you), seems like the goroutine is not necessary another thread but some situations it can call a new thread.