-
Notifications
You must be signed in to change notification settings - Fork 1
/
semaphore_test.go
81 lines (71 loc) · 1.49 KB
/
semaphore_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
73
74
75
76
77
78
79
80
81
package tunnel
import (
"github.com/stretchr/testify/assert"
"sync"
"testing"
"time"
)
func TestSemaphore(t *testing.T) {
sm := NewSemaphore(10)
for i := 0; i < 5; i++ {
assert.Nil(t, sm.Acquire())
}
sm.Close()
// Only half remains in the buffer
assert.Equal(t, 5, sm.count())
for i := 0; i < 5; i++ {
sm.Release()
}
assert.Equal(t, 10, sm.count())
sm.Wait()
}
func TestSemaphoreBufferOne(t *testing.T) {
sm := NewSemaphore(1)
assert.Nil(t, sm.Acquire())
sm.Close()
err := sm.Acquire()
assert.NotNil(t, err)
assert.Equal(t, err, ErrClosedSemaphore)
sm.Release()
sm.Wait()
assert.Equal(t, 1, sm.count())
}
func TestSemaphoreAcquiredAll(t *testing.T) {
sm := NewSemaphore(10)
for i := 0; i < 10; i++ {
assert.Nil(t, sm.Acquire())
}
sm.Close()
err := sm.Acquire()
assert.NotNil(t, err)
assert.Equal(t, err, ErrClosedSemaphore)
go func() {
for i := 0; i < 10; i++ {
sm.Release()
}
}()
sm.Wait()
}
func TestSemaphoreThreaded(t *testing.T) {
// This test should take roughly 1 second because we have 10 resources
// in the semaphore, and 100 goroutines attempting to acquire those
// resources, and each goroutine takes 100 ms to complete.
sm := NewSemaphore(10)
wg := &sync.WaitGroup{}
wg.Add(100)
for i := 0; i < 100; i++ {
go func() {
defer wg.Done()
if sm.Acquire() != nil {
return
}
defer sm.Release()
// some long operation
time.Sleep(100 * time.Millisecond)
}()
}
wg.Wait()
sm.Close()
sm.Wait()
assert.Equal(t, 10, sm.count())
}