# 编译出带检测的程序 $go build -race # 跑test时带检测功能 $go test -race # 直接允许也可以添加 $go run -race main.go
举例
模拟非法竞态访问数据的demo如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
package main
import"fmt"
funcmain() { c := make(chanbool) m := make(map[string]string) gofunc() { m["1"] = "a"// First conflicting access. c <- true }() m["2"] = "b"// Second conflicting access. <-c for k, v := range m { fmt.Println(k, v) } }
================== WARNING: DATA RACE Write at 0x00c00008a180 by goroutine 6: runtime.mapassign_faststr() /usr/local/go/src/runtime/map_faststr.go:190 +0x0 main.main.func1() /Users/chef/Documents/sss/gopath/src/github.com/q191201771/snippet/demo1/main.go:9 +0x5d
Previous write at 0x00c00008a180 by main goroutine: runtime.mapassign_faststr() /usr/local/go/src/runtime/map_faststr.go:190 +0x0 main.main() /Users/chef/Documents/sss/gopath/src/github.com/q191201771/snippet/demo1/main.go:12 +0xc9
Goroutine 6 (running) created at: main.main() /Users/chef/Documents/sss/gopath/src/github.com/q191201771/snippet/demo1/main.go:8 +0x9a ================== 2 b 1 a Found 1 data race(s)