ConcurrentDict Remove add decreaseCount

This commit is contained in:
liyuxing
2021-07-01 10:46:42 +08:00
committed by finley
parent af0ffe6e83
commit 453fef5de1
2 changed files with 17 additions and 3 deletions

View File

@@ -168,6 +168,7 @@ func (dict *ConcurrentDict) Remove(key string) (result int) {
if _, ok := shard.m[key]; ok {
delete(shard.m, key)
dict.decreaseCount()
return 1
}
return 0
@@ -177,6 +178,10 @@ func (dict *ConcurrentDict) addCount() int32 {
return atomic.AddInt32(&dict.count, 1)
}
func (dict *ConcurrentDict) decreaseCount() int32 {
return atomic.AddInt32(&dict.count, -1)
}
// ForEach traversal the dict
// it may not visits new entry inserted during traversal
func (dict *ConcurrentDict) ForEach(consumer Consumer) {

View File

@@ -116,14 +116,17 @@ func TestConcurrentPutIfExists(t *testing.T) {
func TestConcurrentRemove(t *testing.T) {
d := MakeConcurrent(0)
totalCount := 100
// remove head node
for i := 0; i < 100; i++ {
for i := 0; i < totalCount; i++ {
// insert
key := "k" + strconv.Itoa(i)
d.Put(key, i)
}
for i := 0; i < 100; i++ {
if d.Len()!=totalCount{
t.Error("put test failed: expected len is 100, actual: " + strconv.Itoa(d.Len()))
}
for i := 0; i < totalCount; i++ {
key := "k" + strconv.Itoa(i)
val, ok := d.Get(key)
@@ -140,6 +143,9 @@ func TestConcurrentRemove(t *testing.T) {
if ret != 1 {
t.Error("remove test failed: expected result 1, actual: " + strconv.Itoa(ret) + ", key:" + key)
}
if d.Len()!=totalCount-i-1{
t.Error("put test failed: expected len is 99, actual: " + strconv.Itoa(d.Len()))
}
_, ok = d.Get(key)
if ok {
t.Error("remove test failed: expected true, actual false")
@@ -148,6 +154,9 @@ func TestConcurrentRemove(t *testing.T) {
if ret != 0 {
t.Error("remove test failed: expected result 0 actual: " + strconv.Itoa(ret))
}
if d.Len()!=totalCount-i-1{
t.Error("put test failed: expected len is 99, actual: " + strconv.Itoa(d.Len()))
}
}
// remove tail node