Skip to content

Instantly share code, notes, and snippets.

@codahale
Created June 16, 2014 00:27
Show Gist options
  • Save codahale/115eae099139e4fed0bb to your computer and use it in GitHub Desktop.
Save codahale/115eae099139e4fed0bb to your computer and use it in GitHub Desktop.
Only you can prevent race conditions.
package blah
import (
"sync/atomic"
)
var (
n uint64
)
func UnsafeBlah() uint64 {
n = n + 1
return n
}
func SafeBlah() uint64 {
return atomic.AddUint64(&n, 1)
}
package blah
import "testing"
func BenchmarkUnsafeBlah(b *testing.B) {
var u uint64
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
u += UnsafeBlah()
}
})
_ = u
}
func BenchmarkSafeBlah(b *testing.B) {
var u uint64
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
u += SafeBlah()
}
})
_ = u
}
go test -v -bench=. -race -cpu 1,2,4,8
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment