Skip to content

Instantly share code, notes, and snippets.

@taotetek
Created June 6, 2015 14:01
Show Gist options
  • Save taotetek/d735e9ca463cfb404e1f to your computer and use it in GitHub Desktop.
Save taotetek/d735e9ca463cfb404e1f to your computer and use it in GitHub Desktop.
mutex cost
package goczmq
import (
"sync"
"testing"
)
// WITHOUT MUTEX
type WithoutMutex struct {
value int
}
func (w *WithoutMutex) Set(val int) {
w.value = val
}
func (w *WithoutMutex) Get() int {
return w.value
}
func BenchmarkSetGet(b *testing.B) {
w := &WithoutMutex{value: 0}
for i := 0; i < b.N; i++ {
w.Set(i)
n := w.Get()
if n != i {
panic("wrong number")
}
}
}
// WITH MUTEX
type WithMutex struct {
value int
m *sync.Mutex
}
func (w *WithMutex) Set(val int) {
w.m.Lock()
w.value = val
w.m.Unlock()
}
func (w *WithMutex) Get() int {
w.m.Lock()
defer w.m.Unlock()
return w.value
}
func BenchmarkSetGetMutex(b *testing.B) {
w := &WithMutex{value: 0, m: &sync.Mutex{}}
for i := 0; i < b.N; i++ {
w.Set(i)
n := w.Get()
if n != i {
panic("wrong number")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment