-
Notifications
You must be signed in to change notification settings - Fork 2
/
workers_example_test.go
77 lines (74 loc) · 2.1 KB
/
workers_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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package workers
import (
"context"
"fmt"
"time"
)
func ExampleNewBufferedPool() {
myProcessingFunc := func(i int) (int, error) {
// Fictional slow processing method
time.Sleep(time.Millisecond)
return i, nil
}
amountOfJobs := 42
// Create a new buffered pool. Note that the result
// types wil be inferred because of the defined
// process function.
bufferedWorkerPool := NewBufferedPool(
context.Background(),
myProcessingFunc,
// Optionally set a given buffer size.
WithBufferSize(amountOfJobs),
)
// Add 42 jobs to the pool
for i := 0; i < amountOfJobs; i++ {
// The job type is inferred as int because of our processing function
// provided in the NewBufferedPool
bufferedWorkerPool.AddJob(i)
}
// Indicate that all jobs are added tot he pool.
bufferedWorkerPool.Done()
// Await the processing results.
res, err := bufferedWorkerPool.AwaitResults()
if err != nil {
panic(err)
}
fmt.Printf("Got: %d results after processing\n", len(res))
// Output: Got: 42 results after processing
}
func ExampleNewUnBufferedPool() {
myProcessingFunc := func(i int) (int, error) {
// Fictional slow processing method
time.Sleep(time.Millisecond)
return i, nil
}
amountOfJobs := 42
// Create a new buffered pool. Note that the result
// types wil be inferred because of the defined
// process function.
bufferedWorkerPool := NewBufferedPool(
context.Background(),
myProcessingFunc,
// Optionally set a given buffer size.
WithBufferSize(amountOfJobs),
)
// Since we have an unbuffered pool make sure that jobs are added
// in a goroutine, to prevent a deadlock.
go func() {
// Add 42 jobs to the pool
for i := 0; i < amountOfJobs; i++ {
// The job type is inferred as int because of our processing function
// provided in the NewBufferedPool
bufferedWorkerPool.AddJob(i)
}
// Indicate that all jobs are added tot he pool.
bufferedWorkerPool.Done()
}()
// Await the processing results.
res, err := bufferedWorkerPool.AwaitResults()
if err != nil {
panic(err)
}
fmt.Printf("Got: %d results after processing\n", len(res))
// Output: Got: 42 results after processing
}