Created
June 6, 2015 14:01
-
-
Save taotetek/d735e9ca463cfb404e1f to your computer and use it in GitHub Desktop.
mutex cost
This file contains hidden or 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 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