funcmain() { a := 222 gofunc() { a = 666 }() a = 888 fmt.Println("a is ", a)
time.Sleep(2 * time.Second) }
go func触发的goroutine和主goroutine都可能对a进行修改
go run -race demo.go:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
a is 888 ================== WARNING: DATA RACE Write at 0x00c0000ba008 by goroutine 7: main.main.func1() /Users/fliter/go/src/shuang/racee/demo.go:11 +0x28
Previous write at 0x00c0000ba008 by main goroutine: main.main() /Users/fliter/go/src/shuang/racee/demo.go:13 +0x70
Goroutine 7 (running) created at: main.main() /Users/fliter/go/src/shuang/racee/demo.go:10 +0x64 ==================
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 0x00c0000a4180 by goroutine 7: runtime.mapaccess2_faststr() /usr/local/go/src/runtime/map_faststr.go:107 +0x48c main.main.func1() /Users/fliter/go/src/shuang/racee/demo2.go:9 +0x48
Previous write at 0x00c0000a4180 by main goroutine: runtime.mapaccess2_faststr() /usr/local/go/src/runtime/map_faststr.go:107 +0x48c main.main() /Users/fliter/go/src/shuang/racee/demo2.go:12 +0x9c
Goroutine 7 (running) created at: main.main() /Users/fliter/go/src/shuang/racee/demo2.go:8 +0x70 ================== 1 a 2 b Found 1 data race(s) exit status 66
================== WARNING: DATA RACE Read at 0x00c00009a000 by goroutine 7: runtime.evacuate_fast32() /usr/local/go/src/runtime/map_fast32.go:373 +0x37c main.main.func2() /Users/fliter/go/src/run/racee.go:15 +0x3c
Previous write at 0x00c00009a000 by goroutine 6: runtime.mapaccess1_fast64() /usr/local/go/src/runtime/map_fast64.go:12 +0x1ec main.main.func1() /Users/fliter/go/src/run/racee.go:8 +0x38
Goroutine 7 (running) created at: main.main() /Users/fliter/go/src/run/racee.go:13 +0x64
Goroutine 6 (running) created at: main.main() /Users/fliter/go/src/run/racee.go:6 +0x44 ================== fatal error: concurrent map read and map write Found 1 data race(s) exit status 66