Go WaitGroup: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 27: Line 27:
fmt.Println("main is done")
fmt.Println("main is done")
</syntaxhighlight>
</syntaxhighlight>
Result:
<font size=-1>
B
A
main is done
</font>


Note that the <code>WaitGroup</code> instance must be passed to the functions executed on the counted goroutines '''by pointer''', not value. <font color=darkkhaki>Why?</font>
Note that the <code>WaitGroup</code> instance must be passed to the functions executed on the counted goroutines '''by pointer''', not value. <font color=darkkhaki>Why?</font>

Revision as of 21:39, 1 September 2023

External

Internal

Overview

A WaitGroup is a counting semaphore that waits for a set of goroutines to finish.

The main goroutine calls Add() to set the number of goroutines to wait for. Then it can block on Wait() until all other goroutines have finished. When each of the counted goroutines runs, they should call Done() when finished, to increment 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. Why?