-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample_full_test.go
54 lines (46 loc) · 1.09 KB
/
example_full_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
package workpool
import (
"fmt"
)
// gen creates a closed channel with the nums arguments.
func gen(nums ...int) <-chan int {
out := make(chan int)
go func() {
for _, n := range nums {
out <- n
}
close(out)
}()
return out
}
// sq connects an input channel to an output channel with a squaring function. If it detects the channel is closed false
// is returned, otherwise it processes one number and returns.
func sq(input <-chan int, output chan<- int) WorkHandler {
return func(abort <-chan struct{}) bool {
for number := range input {
output <- number * number
return true
}
return false
}
}
func ExampleWorkPool() {
// Closed input channel with three values.
var input <-chan int = gen(2, 3, 10)
// Output channel for results.
output := make(chan int)
// Close function called when pool exits.
closer := func() {
close(output)
}
// Create a pool using a squaring function WorkHandler and a single worker.
pool := NewWithClose(1, sq(input, output), closer)
go pool.Run()
// Check results
for num := range output {
fmt.Println(num)
}
// Output: 4
// 9
// 100
}