From 3e2dc1f49487b333e8f80872f32c593e98d5a816 Mon Sep 17 00:00:00 2001 From: phuslu Date: Sun, 24 Sep 2023 15:05:55 +0800 Subject: [PATCH] add race test, see https://github.com/cornelk/hashmap/issues/73 and https://github.com/alphadose/haxmap/issues/32 --- map_test.go | 81 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) diff --git a/map_test.go b/map_test.go index 53d3f51..e4faeba 100644 --- a/map_test.go +++ b/map_test.go @@ -8,6 +8,7 @@ import ( "fmt" "math/rand" "strconv" + "sync" "testing" "time" ) @@ -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() + } + +}