Skip to content
This repository has been archived by the owner on Feb 6, 2024. It is now read-only.

Commit

Permalink
refactor: implement entry lock (#149)
Browse files Browse the repository at this point in the history
  • Loading branch information
ZuLiangWang authored and ShiKaiWi committed Apr 20, 2023
1 parent c0872b8 commit 9ee58dc
Show file tree
Hide file tree
Showing 2 changed files with 96 additions and 0 deletions.
54 changes: 54 additions & 0 deletions server/coordinator/lock/entry_lock.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// Copyright 2023 CeresDB Project Authors. Licensed under Apache-2.0.

package lock

import (
"fmt"
"sync"
)

type EntryLock struct {
lock sync.Mutex
entryLocks map[uint64]struct{}
}

func NewEntryLock(initCapacity int) EntryLock {
return EntryLock{
entryLocks: make(map[uint64]struct{}, initCapacity),
}
}

func (l *EntryLock) TryLock(locks []uint64) bool {
l.lock.Lock()
defer l.lock.Unlock()

for _, lock := range locks {
_, exists := l.entryLocks[lock]
if exists {
return false
}
}

for _, lock := range locks {
l.entryLocks[lock] = struct{}{}
}

return true
}

func (l *EntryLock) UnLock(locks []uint64) {
l.lock.Lock()
defer l.lock.Unlock()

for _, lock := range locks {
_, exists := l.entryLocks[lock]
if !exists {
panic(fmt.Sprintf("try to unlock nonexistent lock, exists locks:%v, unlock locks:%v", l.entryLocks, locks))
}
}

for _, lock := range locks {
delete(l.entryLocks, lock)
}

}
42 changes: 42 additions & 0 deletions server/coordinator/lock/entry_lock_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// Copyright 2023 CeresDB Project Authors. Licensed under Apache-2.0.

package lock

import (
"testing"

"github.com/stretchr/testify/require"
)

func TestEntryLock(t *testing.T) {
re := require.New(t)

lock := NewEntryLock(3)

lock1 := []uint64{1}
result := lock.TryLock(lock1)
re.Equal(true, result)
result = lock.TryLock(lock1)
re.Equal(false, result)
lock.UnLock(lock1)
result = lock.TryLock(lock1)
re.Equal(true, result)
lock.UnLock(lock1)

lock2 := []uint64{2, 3, 4}
lock3 := []uint64{3, 4, 5}
result = lock.TryLock(lock2)
re.Equal(true, result)
result = lock.TryLock(lock2)
re.Equal(false, result)
result = lock.TryLock(lock3)
re.Equal(false, result)
lock.UnLock(lock2)
result = lock.TryLock(lock2)
re.Equal(true, result)
lock.UnLock(lock2)

re.Panics(func() {
lock.UnLock(lock2)
}, "this function did not panic")
}

0 comments on commit 9ee58dc

Please sign in to comment.