Skip to content

Commit

Permalink
Export KeyRWMutex
Browse files Browse the repository at this point in the history
  • Loading branch information
k1LoW committed Jan 17, 2024
1 parent d4957d0 commit 2db2973
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 13 deletions.
18 changes: 9 additions & 9 deletions keyrwmutex.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,40 +8,40 @@ import (
"k8s.io/utils/keymutex"
)

var _ keymutex.KeyMutex = (*keyRWMutex)(nil)
var _ keymutex.KeyMutex = (*KeyRWMutex)(nil)

type keyRWMutex struct {
type KeyRWMutex struct {
mutexes []sync.RWMutex
}

func New(n int) *keyRWMutex {
func New(n int) *KeyRWMutex {
if n <= 0 {
n = runtime.NumCPU()
}
return &keyRWMutex{
return &KeyRWMutex{
mutexes: make([]sync.RWMutex, n),
}
}

func (km *keyRWMutex) LockKey(key string) {
func (km *KeyRWMutex) LockKey(key string) {
km.mutexes[km.hash(key)%uint32(len(km.mutexes))].Lock()
}

func (km *keyRWMutex) UnlockKey(key string) error {
func (km *KeyRWMutex) UnlockKey(key string) error {
km.mutexes[km.hash(key)%uint32(len(km.mutexes))].Unlock()
return nil
}

func (km *keyRWMutex) RLockKey(key string) {
func (km *KeyRWMutex) RLockKey(key string) {
km.mutexes[km.hash(key)%uint32(len(km.mutexes))].RLock()
}

func (km *keyRWMutex) RUnlockKey(key string) error {
func (km *KeyRWMutex) RUnlockKey(key string) error {
km.mutexes[km.hash(key)%uint32(len(km.mutexes))].RUnlock()
return nil
}

func (km *keyRWMutex) hash(id string) uint32 {
func (km *KeyRWMutex) hash(id string) uint32 {
h := fnv.New32a()
h.Write([]byte(id))
return h.Sum32()
Expand Down
8 changes: 4 additions & 4 deletions keyrwmutex_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ const (
callbackTimeout = 1 * time.Second
)

func newKeyMutexes() []*keyRWMutex {
return []*keyRWMutex{
func newKeyMutexes() []*KeyRWMutex {
return []*KeyRWMutex{
New(0),
New(1),
New(2),
Expand Down Expand Up @@ -129,12 +129,12 @@ func Test_Lock_RLock(t *testing.T) {
}
}

func lockAndCallback(km *keyRWMutex, id string, callbackCh chan<- interface{}) {
func lockAndCallback(km *KeyRWMutex, id string, callbackCh chan<- interface{}) {
km.LockKey(id)
callbackCh <- true
}

func rLockAndCallback(km *keyRWMutex, id string, callbackCh chan<- interface{}) {
func rLockAndCallback(km *KeyRWMutex, id string, callbackCh chan<- interface{}) {
km.RLockKey(id)
callbackCh <- true
}
Expand Down

0 comments on commit 2db2973

Please sign in to comment.