Search code examples
goconcurrencygoroutine

Benefit of using multiple goroutines


I've seen code that waits for a group of goroutines to finish:

var wg sync.WaitGroup
wg.Add(2)
go func() {
    // Do work.
    wg.Done()
}()
go func() {
    // Do some other work.
    wg.Done()
}()
wg.Wait()

What is the main benefit in doing that, rather than let's say:

var wg sync.WaitGroup
wg.Add(1)
go func() {
    // Do work.
    // Do some more work here instead.
    wg.Done()
}()
wg.Wait()

Is it faster?


Solution

  • Some things to clear: both your examples use a single sync.WaitGroup, the main difference is the "distribution" of work to goroutines.

    In your first example you have 2 concurrent goroutines doing 2 different works (tasks), while in the 2nd example you have 1 single goroutine doing both tasks sequentially, one after the other.

    The main benefit may be that the 2 goroutines may be scheduled to run in 2 OS threads, which may utilize 2 separate CPU cores, so it may complete earlier / sooner. Whether it does complete earlier and by how much depends on the actual tasks.

    The 2 tasks may even depend on each other, so it may be that if you put them on a single goroutine they will never complete.