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?

DDD
Release: 2024-11-06 04:59:02
Original
364 people have browsed it

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?

Parallel Processing in Go

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>
Copy after login

Questions:

  1. Can we assume the 'dowork' function will run in parallel?
  2. Is this an appropriate way to achieve parallelism, or should we use channels and separate 'dowork' workers for each goroutine?

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!