通过race监测代码中存在竞争冲突的变量
如何使用go race 监测
go race监测使用比较简单,通过
go run -race test.go
go build -race test.go
当然运行go race监测最好在测试环境上,线上环境不建议使用,因为比较消耗内存和cpu。
go race使用简单示例
test.go
package main
import(
"time"
)
func main() {
a := 1
go func(){
a = 2
}()
a = 3
fmt.Println("a is ", a)
} 正常go run会输出 a is 3 看似没有任何毛病 实际上通过go run -race test.go会出现如下异常
a is 3
==================
WARNING: DATA RACE
Write by goroutine 5:
main.func·001()
/Users/yejianfeng/Documents/workspace/go/src/runtime/test.go:11 +0x3a
Previous write by main goroutine:
main.main()
/Users/yejianfeng/Documents/workspace/go/src/runtime/test.go:13 +0xe7
Goroutine 5 (running) created at:
main.main()
/Users/yejianfeng/Documents/workspace/go/src/runtime/test.go:12 +0xd7
==================
Found 1 data race(s)
exit status 66