Skip to content

Commit

Permalink
add race test, see cornelk/hashmap#73 and alphadose/haxmap#32
Browse files Browse the repository at this point in the history
  • Loading branch information
phuslu committed Sep 24, 2023
1 parent 6b26001 commit 3e2dc1f
Showing 1 changed file with 81 additions and 0 deletions.
81 changes: 81 additions & 0 deletions map_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"fmt"
"math/rand"
"strconv"
"sync"
"testing"
"time"
)
Expand Down Expand Up @@ -312,3 +313,83 @@ func TestClear(t *testing.T) {
}

}

// see https://github.com/cornelk/hashmap/issues/73
func BenchmarkHashMap_RaceCase1(b *testing.B) {
const (
elementNum0 = 1024
iter0 = 8
)
b.StopTimer()
wg := sync.WaitGroup{}
for i := 0; i < b.N; i++ {
var M Map[int, int]
b.StartTimer()
for k := 0; k < iter0; k++ {
wg.Add(1)
go func(l, h int) {
for j := l; j < h; j++ {
M.Set(j, j)
}
for j := l; j < h; j++ {
_, a := M.Get(j)
if !a {
b.Error("key doesn't exist", j)
}
}
for j := l; j < h; j++ {
x, _ := M.Get(j)
if x != j {
b.Error("incorrect value", j, x)
}
}
wg.Done()
}(k*elementNum0, (k+1)*elementNum0)
}
wg.Wait()
b.StopTimer()
}
}

func BenchmarkHashMap_RaceCase3(b *testing.B) {
const (
elementNum0 = 1024
iter0 = 8
)
b.StopTimer()
wg := &sync.WaitGroup{}
for a := 0; a < b.N; a++ {
var M Map[int, int]
b.StartTimer()
for j := 0; j < iter0; j++ {
wg.Add(1)
go func(l, h int) {
defer wg.Done()
for i := l; i < h; i++ {
M.Set(i, i)
}

for i := l; i < h; i++ {
_, x := M.Get(i)
if !x {
b.Errorf("not put: %v\n", i)
}
}
for i := l; i < h; i++ {
M.Delete(i)

}
for i := l; i < h; i++ {
_, x := M.Get(i)
if x {
b.Errorf("not removed: %v\n", i)
}
}

}(j*elementNum0, (j+1)*elementNum0)
}
wg.Wait()
b.StopTimer()
}

}

0 comments on commit 3e2dc1f

Please sign in to comment.