Skip to content

Instantly share code, notes, and snippets.

@darkhelmet
Created March 28, 2013 05:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save darkhelmet/5260789 to your computer and use it in GitHub Desktop.
Save darkhelmet/5260789 to your computer and use it in GitHub Desktop.
package thash
import (
"sync"
"sync/atomic"
"time"
)
type THashDefer struct {
h map[int]string
m sync.Mutex
}
func NewTHashDefer() *THashDefer {
return &THashDefer{h: make(map[int]string)}
}
func (t *THashDefer) Set(i int, s string) {
t.m.Lock()
defer t.m.Unlock()
t.h[i] = s
}
type THashNoDefer struct {
h map[int]string
m sync.Mutex
}
func NewTHashNoDefer() *THashNoDefer {
return &THashNoDefer{h: make(map[int]string)}
}
func (t *THashNoDefer) Set(i int, s string) {
t.m.Lock()
t.h[i] = s
t.m.Unlock()
}
type THashSpinlock struct {
h map[int]string
i int32
}
func NewTHashSpinlock() *THashSpinlock {
return &THashSpinlock{h: make(map[int]string)}
}
func (t *THashSpinlock) Set(i int, s string) {
for {
if atomic.CompareAndSwapInt32(&t.i, 0, 1) {
break
}
time.Sleep(250 * time.Microsecond)
}
t.h[i] = s
atomic.CompareAndSwapInt32(&t.i, 1, 0)
}
package thash
import (
"runtime"
"sync"
"testing"
)
var nCpus = runtime.NumCPU()
func init() {
runtime.GOMAXPROCS(nCpus)
}
func BenchmarkTHashDefer(b *testing.B) {
var wg sync.WaitGroup
t := NewTHashDefer()
s := "THashDefer"
wg.Add(nCpus)
for cpu := 0; cpu < nCpus; cpu++ {
go func() {
for i := 0; i < b.N; i++ {
t.Set(i, s)
}
wg.Done()
}()
}
wg.Wait()
}
func BenchmarkTHashNoDefer(b *testing.B) {
var wg sync.WaitGroup
t := NewTHashNoDefer()
s := "THashNoDefer"
wg.Add(nCpus)
for cpu := 0; cpu < nCpus; cpu++ {
go func() {
for i := 0; i < b.N; i++ {
t.Set(i, s)
}
wg.Done()
}()
}
wg.Wait()
}
func BenchmarkTHashSpinlock(b *testing.B) {
var wg sync.WaitGroup
t := NewTHashSpinlock()
s := "THashSpinlock"
wg.Add(nCpus)
for cpu := 0; cpu < nCpus; cpu++ {
go func() {
for i := 0; i < b.N; i++ {
t.Set(i, s)
}
wg.Done()
}()
}
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment