Skip to content

Instantly share code, notes, and snippets.

@patrickmn
Created February 17, 2012 01:01
Show Gist options
  • Save patrickmn/1849411 to your computer and use it in GitHub Desktop.
Save patrickmn/1849411 to your computer and use it in GitHub Desktop.
atomic.StoreInt32 vs. sync.Mutex
package main
// GOMAXPROCS=4 go test --bench=. --parallel=1
import (
"sync"
"sync/atomic"
"testing"
)
const concurrent = 10
var (
recording int32
mu = sync.Mutex{}
)
func set(s bool) {
if s {
atomic.StoreInt32(&recording, 1)
} else {
atomic.StoreInt32(&recording, 0)
}
}
func get() bool {
return atomic.LoadInt32(&recording) == 1
}
func one(t int) {
for i := 0; i < t; i++ {
set(true)
get()
set(false)
get()
}
}
func mset(s bool) {
mu.Lock()
if s {
recording = 1
} else {
recording = 0
}
mu.Unlock()
}
func mget() bool {
mu.Lock()
is := recording == 1
mu.Unlock()
return is
}
func mone(t int) {
for i := 0; i < t; i++ {
mset(true)
mget()
mset(false)
mget()
}
}
func conc(f func(int), n int) {
wg := sync.WaitGroup{}
c := func() {
f(n)
wg.Done()
}
wg.Add(concurrent)
for i := 0; i < concurrent; i++ {
go c()
}
wg.Wait()
}
func BenchmarkAtomicInt32(b *testing.B) {
one(b.N)
}
func BenchmarkMutex(b *testing.B) {
mone(b.N)
}
func BenchmarkConcurrentAtomicInt32(b *testing.B) {
conc(one, b.N)
}
func BenchmarkConcurrentMutex(b *testing.B) {
conc(mone, b.N)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment