Created
March 28, 2013 05:02
-
-
Save darkhelmet/5260789 to your computer and use it in GitHub Desktop.
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 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) | |
} |
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 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