forked from mennanov/limiters
-
Notifications
You must be signed in to change notification settings - Fork 0
/
locks_test.go
44 lines (40 loc) · 918 Bytes
/
locks_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
package limiters_test
import (
"context"
"sync"
"time"
"github.com/mennanov/limiters"
)
func (s *LimitersTestSuite) useLock(lock limiters.DistLocker, shared *int, sleep time.Duration) {
s.NoError(lock.Lock(context.TODO()))
sh := *shared
// Imitate heavy work...
time.Sleep(sleep)
// Check for the race condition.
s.Equal(sh, *shared)
*shared++
s.NoError(lock.Unlock(context.Background()))
}
func (s *LimitersTestSuite) TestDistLockers() {
locks1 := s.distLockers(false)
locks2 := s.distLockers(false)
for k := 0; k < len(locks1); k++ {
var shared int
rounds := 6
sleep := time.Millisecond * 50
for i := 0; i < rounds; i++ {
wg := sync.WaitGroup{}
wg.Add(2)
go func(k int) {
defer wg.Done()
s.useLock(locks1[k], &shared, sleep)
}(k)
go func(k int) {
defer wg.Done()
s.useLock(locks2[k], &shared, sleep)
}(k)
wg.Wait()
}
s.Equal(rounds*2, shared)
}
}