Go WaitGroup

From NovaOrdis Knowledge Base
Revision as of 19:13, 17 January 2024 by Ovidiu (talk | contribs) (→‎Overview)
Jump to navigation Jump to search

External

Internal

Overview

A WaitGroup is a counting semaphore that waits for a set of goroutines to finish. The WaitGroup#Wait() invocation creates a join point in the program. The primitive does not help with collecting the results of the concurrent operations, it just provides execution synchronization. If results need to be collected, use a channel and a select statement instead.

The main goroutine calls Add() to set the number of goroutines to wait for, by incrementing the counting semaphore. Then it blocks on Wait(), or it can do some work and then block on Wait() until all other goroutines have finished. When each of the counted goroutines runs, they should call Done() when finished, to decrement the counting semaphore.

import "sync"

func aFunction(wg *sync.WaitGroup, s string) {
  defer wg.Done()
  fmt.Println(s)
}

...

wg := sync.WaitGroup{}
wg.Add(2)
go aFunction(&wg, "A")
go aFunction(&wg, "B")
wg.Wait()
fmt.Println("main is done")

Result:

B
A
main is done

Note that the WaitGroup instance must be passed to the functions executed on the counted goroutines by pointer, not value, because otherwise a copy of the sync.WaitGroup struct will be made on the secondary goroutine's stack, as all arguments are passed by value, and the Done() will have no effect on the original struct instance.

The same semantics, when just one single goroutine is involved, can be achieved by using an unbuffered channel and discarding the read result:

Unbuffered Channels and Wait Semantics