forked from egonelbre/async
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_test.go
More file actions
111 lines (95 loc) · 1.79 KB
/
example_test.go
File metadata and controls
111 lines (95 loc) · 1.79 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package async_test
import (
"fmt"
"time"
"github.com/egonelbre/async"
)
func ExampleAll_success() {
result := async.All(
func() error {
time.Sleep(100 * time.Millisecond)
return nil
},
func() error {
time.Sleep(200 * time.Millisecond)
return nil
},
)
select {
case err := <-result.Error:
fmt.Printf("Got an error: %v\n", err)
case <-result.Done:
fmt.Printf("Success\n")
}
}
func ExampleAll_failing() {
result := async.All(
func() error {
time.Sleep(100 * time.Millisecond)
return nil
},
func() error {
time.Sleep(200 * time.Millisecond)
return fmt.Errorf("CRASH")
},
)
select {
case err := <-result.Error:
fmt.Printf("Got an error: %v\n", err)
case <-result.Done:
fmt.Printf("Success\n")
}
}
func ExampleAll_multipleErrors() {
result := async.All(
func() error {
return fmt.Errorf("SPLASH")
},
func() error {
return fmt.Errorf("CRASH")
},
)
for err := range result.Error {
fmt.Printf("Got an error: %v\n", err)
}
}
func ExampleSpawn() {
work := make(chan int, 3)
done := make(chan int, 3)
async.Spawn(3, func(id int) {
for v := range work {
done <- v * v
}
}, func() {
close(done)
})
for i := 0; i < 5; i += 1 {
work <- i
}
close(work)
for r := range done {
println(r)
}
}
func ExampleIter() {
input := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
output := make([]int, len(input))
async.Iter(len(input), 2, func(i int) {
output[i] = input[i] * input[i]
})
for i, v := range output {
println(i, input[i], v)
}
}
func ExampleBlockIter() {
input := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
output := make([]int, len(input))
async.BlockIter(len(input), 2, func(start, limit int) {
for i, v := range input[start:limit] {
output[start+i] = v * v
}
})
for i, v := range output {
println(i, input[i], v)
}
}