rename NRWMutex to NameRWMutex

update changelog
This commit is contained in:
Florian Schade
2021-01-19 23:23:41 +01:00
parent 4f80541b9f
commit 873fbcb557
5 changed files with 32 additions and 31 deletions
@@ -4,41 +4,41 @@ import (
"sync"
)
// NRWMutex works the same as RWMutex, the only difference is that it stores mutexes in a map and reuses them.
// NamedRWMutex works the same as RWMutex, the only difference is that it stores mutexes in a map and reuses them.
// It's handy if you want to write-lock, write-unlock, read-lock and read-unlock for specific names only.
type NRWMutex struct {
type NamedRWMutex struct {
pool sync.Pool
mus sync.Map
}
// NewNRWMutex returns a new instance of NRWMutex.
func NewNRWMutex() NRWMutex {
return NRWMutex{pool: sync.Pool{New: func() interface{} {
// NewNamedRWMutex returns a new instance of NamedRWMutex.
func NewNamedRWMutex() NamedRWMutex {
return NamedRWMutex{pool: sync.Pool{New: func() interface{} {
return new(sync.RWMutex)
}}}
}
// Lock locks rw for writing.
func (m *NRWMutex) Lock(name string) {
func (m *NamedRWMutex) Lock(name string) {
m.loadOrStore(name).Lock()
}
// Unlock unlocks rw for writing.
func (m *NRWMutex) Unlock(name string) {
func (m *NamedRWMutex) Unlock(name string) {
m.loadOrStore(name).Unlock()
}
// RLock locks rw for reading.
func (m *NRWMutex) RLock(name string) {
func (m *NamedRWMutex) RLock(name string) {
m.loadOrStore(name).RLock()
}
// RUnlock undoes a single RLock call.
func (m *NRWMutex) RUnlock(name string) {
func (m *NamedRWMutex) RUnlock(name string) {
m.loadOrStore(name).RUnlock()
}
func (m *NRWMutex) loadOrStore(name string) *sync.RWMutex {
func (m *NamedRWMutex) loadOrStore(name string) *sync.RWMutex {
pmu := m.pool.Get()
mmu, loaded := m.mus.LoadOrStore(name, pmu)
if loaded {
@@ -6,7 +6,7 @@ import (
"testing"
)
func HammerMutex(m *NRWMutex, loops int, c chan bool) {
func HammerMutex(m *NamedRWMutex, loops int, c chan bool) {
for i := 0; i < loops; i++ {
id := fmt.Sprintf("%v", i)
m.Lock(id)
@@ -15,12 +15,12 @@ func HammerMutex(m *NRWMutex, loops int, c chan bool) {
c <- true
}
func TestNRWMutex(t *testing.T) {
func TestNamedRWMutex(t *testing.T) {
if n := runtime.SetMutexProfileFraction(1); n != 0 {
t.Logf("got mutexrate %d expected 0", n)
}
defer runtime.SetMutexProfileFraction(0)
m := NewNRWMutex()
m := NewNamedRWMutex()
c := make(chan bool)
r := 10