update gmutex and its benchmark test cases

This commit is contained in:
John
2019-06-22 14:42:27 +08:00
parent 9a507b54d7
commit 6ee6c007c5
2 changed files with 46 additions and 27 deletions

View File

@ -120,7 +120,6 @@ func (m *Mutex) RUnlock() {
if n == 1 && m.writer.Val() > 0 {
// No readers blocked, then the writers can take place.
m.writing <- struct{}{}
return
}
}
@ -162,6 +161,26 @@ func (m *Mutex) IsRLocked() bool {
return m.state.Val() > 0
}
// LockFunc locks the mutex for writing with given callback function <f>.
// If there's a write/reading lock the mutex, it will blocks until the lock is released.
//
// It releases the lock after <f> is executed.
func (m *Mutex) LockFunc(f func()) {
m.Lock()
defer m.Unlock()
f()
}
// RLockFunc locks the mutex for reading with given callback function <f>.
// If there's a writing lock the mutex, it will blocks until the lock is released.
//
// It releases the lock after <f> is executed.
func (m *Mutex) RLockFunc(f func()) {
m.RLock()
defer m.RUnlock()
f()
}
// TryLockFunc tries locking the mutex for writing with given callback function <f>.
// it returns true if success, or if there's a write/reading lock on the mutex,
// it returns false.
@ -188,23 +207,3 @@ func (m *Mutex) TryRLockFunc(f func()) bool {
}
return false
}
// LockFunc locks the mutex for writing with given callback function <f>.
// If there's a write/reading lock the mutex, it will blocks until the lock is released.
//
// It releases the lock after <f> is executed.
func (m *Mutex) LockFunc(f func()) {
m.Lock()
defer m.Unlock()
f()
}
// RLockFunc locks the mutex for reading with given callback function <f>.
// If there's a writing lock the mutex, it will blocks until the lock is released.
//
// It releases the lock after <f> is executed.
func (m *Mutex) RLockFunc(f func()) {
m.RLock()
defer m.RUnlock()
f()
}

View File

@ -14,21 +14,29 @@ import (
)
var (
mu = sync.RWMutex{}
gmu = gmutex.New()
mu = sync.Mutex{}
rwmu = sync.RWMutex{}
gmu = gmutex.New()
)
func Benchmark_Sync_LockUnlock(b *testing.B) {
func Benchmark_Mutex_LockUnlock(b *testing.B) {
for i := 0; i < b.N; i++ {
mu.Lock()
mu.Unlock()
}
}
func Benchmark_Sync_RLockRUnlock(b *testing.B) {
func Benchmark_RWMutex_LockUnlock(b *testing.B) {
for i := 0; i < b.N; i++ {
mu.RLock()
mu.RUnlock()
rwmu.Lock()
rwmu.Unlock()
}
}
func Benchmark_RWMutex_RLockRUnlock(b *testing.B) {
for i := 0; i < b.N; i++ {
rwmu.RLock()
rwmu.RUnlock()
}
}
@ -39,9 +47,21 @@ func Benchmark_GMutex_LockUnlock(b *testing.B) {
}
}
func Benchmark_GMutex_TryLock(b *testing.B) {
for i := 0; i < b.N; i++ {
gmu.TryLock()
}
}
func Benchmark_GMutex_RLockRUnlock(b *testing.B) {
for i := 0; i < b.N; i++ {
gmu.RLock()
gmu.RUnlock()
}
}
func Benchmark_GMutex_TryRLock(b *testing.B) {
for i := 0; i < b.N; i++ {
gmu.TryRLock()
}
}