[go] Multithread in my program


(ext) #1

Hi guys today I would like to ask you to help see the code. I would like to make the application multithreaded. How can i do this? here is the code

I have this structure.

type Sre struct {
		Name     string `json:"Namesre"`
		Url      string `json:"Url"`
		P_name   string `json:"P_name"`
		P_email  string `json:"P_email"`
		Other    string `json:"Other_params"`
		Create string `json:"Create"`
		Base    string `json:"Base"`
	}

	type Settings struct {
		Sres []Sre
	}
    
    var settings Settings

ok. And I have for example 100 elements settings.Sres[100]

In the normal case, I would use the for loop and go through all the elements in turn. Well, how to implement it using multithreading ?

for i := 0; i < len(settings.Sres); i++ {
    go Other(settings.Sres[I].Name,
        settings.Sres[I].Url,
        settings.Sres[I].P_name,
        settings.Sres[I].P_email,
        settings.Sres[I].Other,
        settings.Sres[I].Create,
        settings.Sres[I].Base)
}
func Other{param1 string, param2 string, param3 string, param4 string, param5 string, param6 string,param7 string
{
....
....
....
}

Please tell me how I can create 100 threads execute to process all elements (settings.Sres [100]) in the Other function simultaneously in 100 threads


(Norbert Melzer) #2

In go there is a limited number of threads, which are managed by the runtime. Those threads will be used to run your go-routines.

To me it seems as if you already have the code as concurrent as possible.

You are starting one go-routine for each element and process them concurrently.


edit

It might be easier to read though if you were passing a Sre to Other() rather than each of its fields separetly.


(ext) #3

thx, I agree, yes i can completely transfer the structure to a function, but I still don’t understand how to attach multithreading without a for loop( I go read manuals=)


(Norbert Melzer) #4

You need the loop to start the go-routines. If you want to to it without the loop, you have to write out the line for each element manually. This is impossible if you do not know in advance how many items you’ll have.


(ext) #5

Yes, I agree, now I am looking for how to implement this with waitgroup, thank you for the answers