wiki/content/20200918174548-waitgroup.md

55 lines
967 B
Markdown
Raw Permalink Normal View History

2024-05-06 20:40:05 +00:00
---
2024-10-30 17:34:11 +00:00
date: 2020-09-18
2024-05-06 20:40:05 +00:00
id: 53c0ad13-0c19-4a84-9c67-cc31d036be4d
title: Golang WaitGroup
---
# Description
A [WaitGroup](https://golang.org/pkg/sync/#WaitGroup) waits for a
collection of goroutines to finish. The main goroutine calls Add to set
the number of goroutines to wait for. Then each of the goroutines runs
and calls Done when finished. At the same time, Wait can be used to
block until all goroutines have finished.
A WaitGroup must not be copied after first use.
# Syntax
``` go
type Counter struct {
mu sync.Mutex
value int
}
func (c *Counter) Inc() {
c.mu.Lock()
defer c.mu.Unlock()
c.value++
}
func (c *Counter) Value() int {
return c.value
}
func NewCounter() *Counter {
return &Counter{}
}
wantedCount := 1000
counter := NewCounter()
var wg sync.WaitGroup
wg.Add(wantedCount)
for i := 0; i < wantedCount; i++ {
go func(w *sync.WaitGroup) {
counter.Inc()
w.Done()
}(&wg)
}
wg.Wait()
```