package main import ( "fmt" "sync/atomic" ) var ( // 序列號 seq int64 ) // 序列號生成器 func GenID() int64 { // 嘗試原子的增加序列號 atomic.AddInt64(&seq, 1) return seq } func main() { //生成10個並行序列號 for i := 0; i < 10; i++ { go GenID() } fmt.Println(GenID()) }程式碼說明如下:
-race
引數,開啟執行時(runtime)對競態問題的分析,命令如下:
go run -race racedetect.go
程式碼執行發生宕機,輸出資訊如下:
==================
WARNING: DATA RACE
Write at 0x000000f52f40 by goroutine 7:
sync/atomic.AddInt64()
C:/Go/src/runtime/race_amd64.s:276 +0xb
main.GenID()
racedetect.go:17 +0x4a
Previous read at 0x000000f52f40 by goroutine 6:
main.GenID()
racedetect.go:18 +0x5a
Goroutine 7 (running) created at:
main.main()
racedetect.go:25 +0x5a
Goroutine 6 (finished) created at:
main.main()
racedetect.go:25 +0x5a
==================
10
Found 1 data race(s)
exit status 66
func GenID() int64 { // 嘗試原子的增加序列號 return atomic.AddInt64(&seq, 1) }再次執行:
go run -race main.go
程式碼輸出如下: