Parallel processing in golang

Issue

Given the following code:

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)
}

Can i assume that the ‘dowork’ function will be executed in parallel?

Is this a correct way of achieving parallelism or is it better to use channels and separate ‘dowork’ workers for each goroutine?

Solution

This answer is outdated. Please see this answer instead.


Your code will run concurrently, but not in parallel. You can make it run in parallel by setting GOMAXPROCS.

It’s not clear exactly what you’re trying to accomplish here, but it looks like a perfectly valid way of achieving concurrency to me.

Answered By – Evan

Answer Checked By – Terry (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.