Skip to content

Instantly share code, notes, and snippets.

@rhcarvalho
Created March 29, 2016 19:57
Show Gist options
  • Save rhcarvalho/6811c2d0760f0fcce476cc4c640d2c6b to your computer and use it in GitHub Desktop.
Save rhcarvalho/6811c2d0760f0fcce476cc4c640d2c6b to your computer and use it in GitHub Desktop.
data race example
$ go run -race racy.go
==================
WARNING: DATA RACE
Write by goroutine 5:
main.func·001()
/tmp/racy.go:12 +0x158
Previous read by main goroutine:
main.main()
/tmp/racy.go:15 +0xdb
Goroutine 5 (running) created at:
main.main()
/tmp/racy.go:14 +0xcb
==================
==================
WARNING: DATA RACE
Read by main goroutine:
errors.(*errorString).Error()
/usr/lib/golang/src/errors/errors.go:19 +0x48
fmt.(*pp).handleMethods()
/usr/lib/golang/src/fmt/print.go:714 +0x534
fmt.(*pp).printArg()
/usr/lib/golang/src/fmt/print.go:794 +0x492
fmt.(*pp).doPrint()
/usr/lib/golang/src/fmt/print.go:1218 +0x3a7
fmt.Fprintln()
/usr/lib/golang/src/fmt/print.go:254 +0x7b
fmt.Println()
/usr/lib/golang/src/fmt/print.go:264 +0xab
main.main()
/tmp/racy.go:18 +0x233
Previous write by goroutine 5:
fmt.Errorf()
/usr/lib/golang/src/fmt/print.go:212 +0xcb
main.func·001()
/tmp/racy.go:12 +0x135
Goroutine 5 (running) created at:
main.main()
/tmp/racy.go:14 +0xcb
==================
error: watch error #4
Found 2 data race(s)
exit status 66
package main
import (
"fmt"
"time"
)
func main() {
var watchError error
go func() {
for i := 0; ; i = (i + 1) % 10 {
watchError = fmt.Errorf("watch error #%v", i)
}
}()
for watchError == nil {
time.Sleep(200 * time.Millisecond)
}
fmt.Println("error:", watchError)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment