像这样在一段时间后停止 goroutine 并发安全吗?
(注意:由于另一个 goroutine 发生变化而导致数据竞争):ok
package main
import (
"fmt"
"time"
)
func main() {
var ok byte
time.AfterFunc(1000*time.Millisecond, func() {
ok = 1
})
var i uint64
for ok == 0 {
i++ // CPU intensive task
}
fmt.Println(i) // 2_776_813_033
}
终端:
go run -race .
==================
WARNING: DATA RACE
Write at 0x00c000132010 by goroutine 8:
main.main.func1()
./main.go:11 +0x46
Previous read at 0x00c000132010 by main goroutine:
main.main()
./main.go:15 +0xf4
Goroutine 8 (running) created at:
time.goFunc()
go/src/time/sleep.go:180 +0x51
==================
80849692
Found 1 data race(s)
代码(无数据竞争):
package main
import (
"fmt"
"sync/atomic"
"time"
)
func main() {
var ok int32
time.AfterFunc(1000*time.Millisecond, func() {
atomic.StoreInt32(&ok, 1)
})
var i uint64
for atomic.LoadInt32(&ok) == 0 {
i++ // CPU intensive task
}
fmt.Println(i) // 2_835_935_488
}
终端:
go run -race .
31934042
慕勒3428872
繁花不似锦
相关分类