Race Detector Finds Data Races
Show the unsynchronized counter that the race detector flags under go run -race, and the mutex-guarded version that converges on the same workload.
Code
package main
import (
"fmt"
"sync"
)
func main() {
var counter int
var wg sync.WaitGroup
// 两个 goroutine 无同步地写同一个变量:
// go run -race 会报告 DATA RACE;不带 -race 时更新可能被静默覆盖
wg.Add(2)
go func() {
defer wg.Done()
for i := 0; i < 1000; i++ {
counter++
}
}()
go func() {
defer wg.Done()
for i := 0; i < 1000; i++ {
counter--
}
}()
wg.Wait()
fmt.Println("counter:", counter)
// 正确做法:每次增量都受互斥锁保护,结果恒为 0
var mu sync.Mutex
var safe int
wg.Add(2)
go func() {
defer wg.Done()
for i := 0; i < 1000; i++ {
mu.Lock()
safe++
mu.Unlock()
}
}()
go func() {
defer wg.Done()
for i := 0; i < 1000; i++ {
mu.Lock()
safe--
mu.Unlock()
}
}()
wg.Wait()
fmt.Println("safe:", safe)
}The runtime narrative
What shifts is held in the function main.
The file repeats itself only inside for i := 0; i < 1000; i++. Work is dispatched on a goroutine. defer schedules the cleanup, and the scheduled call fires no matter how the function exits.
Points of care
- There is no install step, because the platform ships every API the code calls.
Applying it
The entry-point signature is func main()
The demo output is labeled (counter:, safe:); each label names the call that printed it.
Statements that matter
var wg sync.WaitGroup
var mu sync.Mutex
defer wg.Done()
Interactive Tools for This Topic
Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.UUID Version DetectorValidate the 8-4-4-4-12 UUID layout and read its version (v1 to v8) and variant nibbles per RFC 9562, with full field decomposition.
FAQ
- What does Race Detector Finds Data Races print when run?
- The script runs standalone; its 2 labeled outputs include `counter:`, `safe:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.