sync.Once, sync.Mutex, sync.WaitGroup
func (o *Once) Do(f func())
func (m *Mutex) Lock()
func (m *Mutex) Unlock()
func (wg *WaitGroup) Add(delta int)
func (wg *WaitGroup) Done()
func (wg *WaitGroup) Wait()Run an initializer once, and wait for a fixed number of goroutines while a Mutex protects a shared counter. This is the Go 1.24 WaitGroup API: Add, Done, and Wait, not WaitGroup.Go.
| Parameter | Description |
|---|---|
f | The function Once.Do may run. Only the first Do call on that Once invokes it. |
delta | A change to the WaitGroup counter. A positive Add that starts from zero must happen before Wait. |
Returns: These methods do not return a value. Wait returns after Done has brought the counter back to zero.
- The three goroutines only communicate through the Mutex-protected sum and the WaitGroup. The printed sum is 3 and does not depend on scheduling order.
- This example was run with go run -race on Go 1.24.0 darwin/arm64, and that race run passed.
package main
import (
"fmt"
"sync"
)
func main() {
var once sync.Once
n := 0
inc := func() { n++ }
once.Do(inc)
once.Do(inc)
fmt.Println(n)
var wg sync.WaitGroup
var mu sync.Mutex
sum := 0
for i := 0; i < 3; i++ {
wg.Add(1)
go func() {
defer wg.Done()
mu.Lock()
sum++
mu.Unlock()
}()
}
wg.Wait()
fmt.Println(sum)
}Expected output
1
3