-
Notifications
You must be signed in to change notification settings - Fork 0
/
counter_test.go
68 lines (59 loc) · 1.32 KB
/
counter_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
package hops_test
import (
"math/rand"
"testing"
"time"
"github.com/ocpodariu/hops"
)
func ExampleCounter() {
// Create a counter to track events from last 5 minutes
c := hops.NewCounter(5, time.Minute)
// Register events as they appear
c.Observe()
c.Observe()
c.Observe()
// Check number of registered events
c.Value()
}
// TestCounterConcurrently is used to check for race conditions when reading
// and updating a counter at the same time.
//
// Run it with the race detector enabled:
// $ go test -race -run TestCounterConcurrently
func TestCounterConcurrently(t *testing.T) {
writer := func(c *hops.Counter, shutdown chan struct{}) {
for {
select {
case <-shutdown:
return
default:
}
c.Observe()
time.Sleep(time.Duration(rand.Intn(5)) * time.Millisecond)
}
}
reader := func(c *hops.Counter, shutdown chan struct{}) {
for {
select {
case <-shutdown:
return
default:
}
c.Value()
time.Sleep(time.Duration(rand.Intn(50)) * time.Millisecond)
}
}
c := hops.NewCounter(5, time.Second)
shutdown := make(chan struct{})
// Start a couple of writers and readers
for i := 0; i < 100; i++ {
go writer(c, shutdown)
}
for i := 0; i < 50; i++ {
go reader(c, shutdown)
}
// Let them run for a while
time.Sleep(10 * time.Second)
close(shutdown)
time.Sleep(time.Second)
}