milvus/pkg/util/lock/key_lock_test.go
congqixia 4a6790b63a
Make KeyLock generic (#27854)
Signed-off-by: Congqi Xia <congqi.xia@zilliz.com>
2023-10-23 17:40:11 +08:00

70 lines
1.1 KiB
Go

package lock
import (
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestKeyLock(t *testing.T) {
keys := []string{"Milvus", "Blazing", "Fast"}
keyLock := NewKeyLock[string]()
keyLock.Lock(keys[0])
keyLock.Lock(keys[1])
keyLock.Lock(keys[2])
// should work
wg := sync.WaitGroup{}
wg.Add(2)
go func() {
keyLock.Lock(keys[0])
keyLock.Unlock(keys[0])
wg.Done()
}()
go func() {
keyLock.Lock(keys[0])
keyLock.Unlock(keys[0])
wg.Done()
}()
assert.Equal(t, keyLock.size(), 3)
time.Sleep(10 * time.Millisecond)
keyLock.Unlock(keys[0])
keyLock.Unlock(keys[1])
keyLock.Unlock(keys[2])
wg.Wait()
assert.Equal(t, keyLock.size(), 0)
}
func TestKeyRLock(t *testing.T) {
keys := []string{"Milvus", "Blazing", "Fast"}
keyLock := NewKeyLock[string]()
keyLock.RLock(keys[0])
keyLock.RLock(keys[0])
// should work
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
keyLock.Lock(keys[0])
keyLock.Unlock(keys[0])
wg.Done()
}()
time.Sleep(10 * time.Millisecond)
keyLock.RUnlock(keys[0])
keyLock.RUnlock(keys[0])
wg.Wait()
assert.Equal(t, keyLock.size(), 0)
}