-
Notifications
You must be signed in to change notification settings - Fork 6
/
example_test.go
70 lines (62 loc) · 1.65 KB
/
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
// SPDX-License-Identifier: Apache-2.0
// Copyright Authors of Cilium
package workerpool_test
import (
"context"
"fmt"
"os"
"runtime"
"github.com/cilium/workerpool"
)
// IsPrime returns true if n is prime, false otherwise.
func IsPrime(n int64) bool {
if n < 2 {
return false
}
for p := int64(2); p*p <= n; p++ {
if n%p == 0 {
return false
}
}
return true
}
func Example() {
wp := workerpool.New(runtime.NumCPU())
for i, n := 0, int64(1_000_000_000_000_000_000); n < 1_000_000_000_000_000_100; i, n = i+1, n+1 {
n := n // https://golang.org/doc/faq#closures_and_goroutines
id := fmt.Sprintf("task #%d", i)
// Use Submit to submit tasks for processing. Submit blocks when no
// worker is available to pick up the task.
err := wp.Submit(id, func(_ context.Context) error {
fmt.Println("isprime", n)
if IsPrime(n) {
fmt.Println(n, "is prime!")
}
return nil
})
// Submit fails when the pool is closed (ErrClosed) or being drained
// (ErrDrained). Check for the error when appropriate.
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
}
// Drain prevents submitting new tasks and blocks until all submitted tasks
// complete.
tasks, err := wp.Drain()
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
// Iterating over the results is useful if non-nil errors can be expected.
for _, task := range tasks {
// Err returns the error that the task returned after execution.
if err := task.Err(); err != nil {
fmt.Println("task", task, "failed:", err)
}
}
// Close should be called once the worker pool is no longer necessary.
if err := wp.Close(); err != nil {
fmt.Fprintln(os.Stderr, err)
}
}