Radar · Go · Archive · Week 4 · Jan 20 – 26, 2025
cmd/vet: add check for sync.WaitGroup abuse
Worth knowingtooling
- What changed
- The vet tool now includes a check that flags a common misuse of
sync.WaitGroupwhereAddis called after a goroutine is started. The check triggers whenwg.Addappears on the first line of a closure. - Production impact
- The source does not say.
- Try it
- Run
go veton a package that contains async.WaitGrouppattern like the one shown in the proposal to see the new warning. - Source
- github.com/golang/go/issues/18022
Understand it, then run it
Run it now
// This program demonstrates the sync.WaitGroup misuse that the vet tool
// now flags. The pattern is:
// go func() { wg.Add(1); defer wg.Done() }()
// The Add happens after the goroutine starts, which can race with wg.Wait
// and may cause the program to exit before the goroutine finishes.
package main
import (
"fmt"
"sync"
"time"
)
func main() {
var wg sync.WaitGroup
// Defer Wait so the main goroutine waits for all workers.
defer wg.Wait()
// Start a goroutine that adds to the WaitGroup after it has begun.
go func() {
// Add is called after the goroutine has already started.
wg.Add(1)
defer wg.Done()
// Simulate work.
time.Sleep(100 * time.Millisecond)
fmt.Println("Worker finished")
}()
// Sleep briefly to allow the goroutine to start before main exits.
time.Sleep(10 * time.Millisecond)
fmt.Println("Main exiting")
}
What it printed when we ran it on Go 1.27.1
Main exiting Worker finished
Run sends this program (for Solidity, the contract and its tests) to our own sandbox, where it is compiled and run once, with no network, and what it printed or the test report comes back here. Nothing is kept. Runs are counted per visitor for the day so everyone gets a turn; the details are on the legal page.
Written by gpt-oss-20b from the linked source · claims checked against the sources · archive, not individually reviewed