-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsemaphore_test.go
40 lines (31 loc) · 941 Bytes
/
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
package semaphore_test
import (
"math/rand"
"runtime"
"testing"
"time"
"github.com/g3offrey/semaphore"
)
func GetRandomDuration(max time.Duration) time.Duration {
return time.Duration(rand.Int63n(int64(max)))
}
func TestSemaphore(t *testing.T) {
capacity := 3
sem := semaphore.Make(capacity)
initialNumberOfGoRoutines := runtime.NumGoroutine()
expectedNumberOfGoRoutines := initialNumberOfGoRoutines + capacity
for i := 0; i < 50; i++ {
sem.Acquire()
go func() {
defer sem.Release()
time.Sleep(GetRandomDuration(100) * time.Millisecond)
if runtime.NumGoroutine() > expectedNumberOfGoRoutines {
t.Errorf("Too many goroutines running concurrently, expecting %d, got %d", expectedNumberOfGoRoutines, runtime.NumGoroutine())
}
}()
}
sem.Wait()
if runtime.NumGoroutine() != initialNumberOfGoRoutines {
t.Errorf("Expected no goroutine, got %d", runtime.NumGoroutine()-initialNumberOfGoRoutines)
}
}