|
|
|
|
|
by jrockway
1496 days ago
|
|
It really depends on where you draw the line. This is an obviously-incorrect program (`++` isn't atomic): func main() {
var x, y int64
doneCh := make(chan struct{})
inc := func() {
for i := 0; i < 2<<20; i++ {
x++ // line 13 in test/main.go
atomic.AddInt64(&y, 1)
}
doneCh <- struct{}{}
return
}
go inc()
go inc()
<-doneCh
<-doneCh
fmt.Printf("x, y = %v, %v\n", x, y)
}
This prints something like: $ go run main.go
x, y = 3482626, 4194304
If you run it with the race detector the problem is clear: $ go run -race main.go
==================
WARNING: DATA RACE
Read at 0x00c0001bc008 by goroutine 7:
main.main.func1()
/home/jrockway/test/main.go:13 +0x50
Previous write at 0x00c0001bc008 by goroutine 8:
main.main.func1()
/home/jrockway/test/main.go:13 +0x64
Goroutine 7 (running) created at:
main.main()
/home/jrockway/test/main.go:19 +0x176
Goroutine 8 (running) created at:
main.main()
/home/jrockway/test/main.go:20 +0x184
==================
x, y = 4189962, 4194304
Found 1 data race(s)
exit status 66
This is not strictly a memory safety problem (this can't crash the runtime), but a program that returns the wrong answer is pretty useless, so there is that. Obviously if x were going to be used as a pointer through the `unsafe` package, you could have problems. (Though I think that x will always be less than y, so if you have proved that memory[base+y] is safe to read, then memory[base+x] is safe to read. But it's easy to imagine a scenario where you overcount instead of undercount. |
|