Go WaitGroup: Difference between revisions
Jump to navigation
Jump to search
Line 8: | Line 8: | ||
A <code>WaitGroup</code> is a [[Concurrent_(Parallel)_Programming#Counting_Semaphore|counting semaphore]] that waits for a set of goroutines to finish. | A <code>WaitGroup</code> is a [[Concurrent_(Parallel)_Programming#Counting_Semaphore|counting semaphore]] that waits for a set of goroutines to finish. | ||
The main goroutine calls <code>Add()</code> to set the number of goroutines to wait for. Then it should block on <code>Wait()</code>, or it can do some work and then block on <code>Wait()</code> until all other goroutines have finished. When each of the counted goroutines runs, they should call <code>Done()</code> when finished, to | The main goroutine calls <code>Add()</code> to set the number of goroutines to wait for. Then it should block on <code>Wait()</code>, or it can do some work and then block on <code>Wait()</code> until all other goroutines have finished. When each of the counted goroutines runs, they should call <code>Done()</code> when finished, to decrement the counting semaphore. | ||
<syntaxhighlight lang='go'> | <syntaxhighlight lang='go'> |
Revision as of 21:46, 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 should block 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.