Skip to content

WaitGroup Add Called Inside Goroutine

Description

Calling `WaitGroup.Add` inside of an anonymous goroutine may result in `WaitGroup.Wait` waiting for more or less calls to `WaitGroup.Done()` than expected. This can lead to improper locking and potential deadlocks or unexpected behavior.

Examples

Insecure Code

go
var wg sync.WaitGroup
//go func() {
  wg.Add(1)
//}()
wg.Wait()

Secure Code

go
var wg sync.WaitGroup
wg.Add(1)
go func() {
  //

Remediation

Ensure that `WaitGroup.Add` is called outside of the anonymous goroutine, or use alternative synchronization primitives that are safe for concurrent access.

Rule Details

FieldValue
IDCODE-0095
CategoryConcurrency
SeverityMEDIUM
CWECWE-667
ConfidenceMEDIUM
ImpactMEDIUM
LikelihoodMEDIUM
ExploitabilityMODERATE
Tagssynchronization, concurrency
OWASPN/A

References