forked from karrick/congomap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
new_test.go
72 lines (57 loc) · 1.37 KB
/
new_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package congomap
import (
"fmt"
"sync"
"testing"
"time"
)
func slowSucceedingLookup(_ string) (interface{}, error) {
time.Sleep(time.Second)
return 42, nil
}
func asyncAccess(cgm Congomap, key string, wg *sync.WaitGroup) (interface{}, error) {
defer wg.Done()
val, ok := cgm.LoadStore(key)
return val, ok
}
func testConcurrentLoad(t *testing.T, cgm Congomap) {
// How many times to access at once
totalTimes := 100
var wg sync.WaitGroup
start := time.Now()
for i := 0; i < totalTimes; i++ {
wg.Add(1)
go asyncAccess(cgm, fmt.Sprintf("test%d", i), &wg)
}
wg.Wait()
elapsed := time.Since(start)
if elapsed > time.Second*2 {
t.Fatalf("Load took too long")
}
var k string
for i := 0; i < totalTimes; i++ {
k = fmt.Sprintf("test%d", i)
val, ok := cgm.Load(k)
if !ok {
t.Fatalf("Key %v missing from congomap %v", k, cgm)
}
if val != 42 {
t.Fatalf("Value for %v incorrect in congomap, expected 42 got %v", k, val)
}
}
}
func TestConcurrentChannel(t *testing.T) {
cgm, _ := NewChannelMap(Lookup(slowSucceedingLookup))
testConcurrentLoad(t, cgm)
cgm.Close()
}
func TestConcurrentMutex(t *testing.T) {
cgm, _ := NewSyncMutexMap(Lookup(slowSucceedingLookup))
testConcurrentLoad(t, cgm)
cgm.Close()
}
func TestConcurrentAtomic(t *testing.T) {
cgm, _ := NewSyncAtomicMap(Lookup(slowSucceedingLookup))
testConcurrentLoad(t, cgm)
cgm.Close()
}