Home >Backend Development >Golang >Is using `go f(i)` the optimal way to achieve parallelism in Go, or should we explore alternative methods like channels and dedicated workers for each goroutine?
Problem:
Consider the given Go code snippet:
<code class="go">package main import ( "fmt" "math/rand" "time" ) func main() { for i := 0; i < 3; i++ { go f(i) } // prevent main from exiting immediately var input string fmt.Scanln(&input) } func f(n int) { for i := 0; i < 10; i++ { dowork(n, i) amt := time.Duration(rand.Intn(250)) time.Sleep(time.Millisecond * amt) } } func dowork(goroutine, loopindex int) { // simulate work time.Sleep(time.Second * time.Duration(5)) fmt.Printf("gr[%d]: i=%d\n", goroutine, loopindex) }</code>
Questions:
Answer:
Regarding GOMAXPROCS:
According to the Go 1.5 release notes:
"By default, Go programs run with GOMAXPROCS set to the number of cores available; in prior releases it defaulted to 1."
Regarding Preventing Main Function Exit:
To prevent the 'main' function from exiting immediately, the 'WaitGroup' type can be utilized, specifically the 'Wait' function.
Regarding Parallelism:
To facilitate parallel processing of groups of functions, a helper function can be employed:
<code class="go">import "sync" // Parallelize executes functions concurrently func Parallelize(functions ...func()) { var waitGroup sync.WaitGroup waitGroup.Add(len(functions)) defer waitGroup.Wait() for _, function := range functions { go func(f func()) { defer waitGroup.Done() f() }(function) } }</code>
In your case, parallelism can be achieved as follows:
<code class="go">func1 := func() { f(0) } func2 = func() { f(1) } func3 = func() { f(2) } Parallelize(func1, func2, func3)</code>
The above is the detailed content of Is using `go f(i)` the optimal way to achieve parallelism in Go, or should we explore alternative methods like channels and dedicated workers for each goroutine?. For more information, please follow other related articles on the PHP Chinese website!