-
Notifications
You must be signed in to change notification settings - Fork 0
/
runnerpool_example_test.go
63 lines (51 loc) · 1.01 KB
/
runnerpool_example_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
package runnerpool_test
import (
"context"
"fmt"
"log"
"sync"
"time"
"github.com/cabify/runnerpool"
)
func ExamplePool() {
const workers = 2
const tasks = workers + 1
const timeout = 250 * time.Millisecond
cfg := runnerpool.Config{
Workers: workers,
}
runner := func(f func()) {
go f()
}
pool := runnerpool.New(cfg, runner)
err := pool.Start()
if err != nil {
log.Fatal(err)
}
wg := sync.WaitGroup{}
wg.Add(tasks)
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
for i := 1; i <= tasks; i++ {
go func(i int) {
time.Sleep(time.Duration(i) * timeout / 10)
worker, err := pool.Worker(ctx)
if err != nil {
fmt.Printf("Can't acquire worker %d\n", i)
wg.Done()
return
}
defer worker.Release()
worker.Run(func(ctx context.Context) {
time.Sleep(time.Duration(i) * timeout * 2)
fmt.Printf("Worker %d done\n", i)
wg.Done()
})
}(i)
}
wg.Wait()
// Output:
// Can't acquire worker 3
// Worker 1 done
// Worker 2 done
}