為什么這段代碼會導(dǎo)致數(shù)據(jù)競爭?我已經(jīng)使用了原子添加。package mainimport ( "sync/atomic" "time")var a int64func main() { for { if a < 100 { atomic.AddInt64(&a, 1) go run() } }}func run() { <-time.After(5 * time.Second) atomic.AddInt64(&a, -1)}我go run --race用這段代碼運(yùn)行命令并得到:==================WARNING: DATA RACEWrite at 0x000001150f30 by goroutine 8: sync/atomic.AddInt64() /usr/local/Cellar/go/1.11.2/libexec/src/runtime/race_amd64.s:276 +0xb main.run() /Users/flask/test.go:22 +0x6dPrevious read at 0x000001150f30 by main goroutine: main.main() /Users/flask/test.go:12 +0x3aGoroutine 8 (running) created at: main.main() /Users/flask/test.go:15 +0x75==================你能幫我解釋一下嗎?以及如何解決此警告?謝謝!
是什么導(dǎo)致了這種數(shù)據(jù)競爭?
阿波羅的戰(zhàn)車
2023-06-01 09:58:48