Created
June 16, 2014 00:27
-
-
Save codahale/115eae099139e4fed0bb to your computer and use it in GitHub Desktop.
Only you can prevent race conditions.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package blah | |
import ( | |
"sync/atomic" | |
) | |
var ( | |
n uint64 | |
) | |
func UnsafeBlah() uint64 { | |
n = n + 1 | |
return n | |
} | |
func SafeBlah() uint64 { | |
return atomic.AddUint64(&n, 1) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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