Created
August 28, 2017 22:42
-
-
Save dtjm/164081e978fa6472d137396614f54673 to your computer and use it in GitHub Desktop.
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 lock_test | |
import ( | |
"fmt" | |
"sync" | |
"testing" | |
"time" | |
) | |
type rlocker interface { | |
sync.Locker | |
RLock() | |
RUnlock() | |
} | |
type noopLock struct{} | |
func (m noopLock) Lock() {} | |
func (m noopLock) Unlock() {} | |
func (m noopLock) RLock() {} | |
func (m noopLock) RUnlock() {} | |
type lockOnlyMutex struct { | |
sync.Mutex | |
} | |
func (m *lockOnlyMutex) RLock() { m.Lock() } | |
func (m *lockOnlyMutex) RUnlock() { m.Unlock() } | |
func BenchmarkLocks(b *testing.B) { | |
mutexes := []rlocker{ | |
&noopLock{}, | |
&lockOnlyMutex{}, | |
&sync.RWMutex{}, | |
} | |
for _, readRatio := range []int{1, 10, 100} { | |
for _, mu := range mutexes { | |
b.Run(fmt.Sprintf("%T,readRatio=%d", mu, readRatio), func(b *testing.B) { | |
b.ResetTimer() | |
benchmarkRLocker(b, mu, readRatio, time.Microsecond, time.Nanosecond) | |
}) | |
} | |
} | |
} | |
func benchmarkRLocker(b *testing.B, mu rlocker, readRatio int, readTime, writeTime time.Duration) { | |
writers := 1 | |
readers := writers * readRatio | |
// mu := sync.Mutex{} | |
wg := sync.WaitGroup{} | |
x := 0 | |
for i := 0; i < readers; i++ { | |
wg.Add(1) | |
go func() { | |
defer wg.Done() | |
for { | |
mu.RLock() | |
y := x | |
time.Sleep(readTime) | |
mu.RUnlock() | |
if y > b.N { | |
return | |
} | |
} | |
}() | |
} | |
for i := 0; i < writers; i++ { | |
wg.Add(1) | |
go func() { | |
defer wg.Done() | |
for { | |
// log.Printf("acquiring write lock") | |
// defer log.Printf("releasing write lock") | |
mu.Lock() | |
time.Sleep(writeTime) | |
x++ | |
done := x > b.N | |
mu.Unlock() | |
if done { | |
return | |
} | |
} | |
}() | |
} | |
wg.Wait() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Results: