This repository has been archived by the owner on Jul 7, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
do_example_test.go
194 lines (179 loc) · 4.06 KB
/
do_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
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
package workgroup_test
import (
"context"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing/fstest"
"time"
"github.com/carlmjohnson/workgroup"
"golang.org/x/exp/maps"
"golang.org/x/exp/slices"
)
func ExampleDo() {
// Example site to crawl with recursive links
srv := httptest.NewServer(http.FileServer(http.FS(fstest.MapFS{
"index.html": &fstest.MapFile{
Data: []byte("/a.html"),
},
"a.html": &fstest.MapFile{
Data: []byte("/b1.html\n/b2.html"),
},
"b1.html": &fstest.MapFile{
Data: []byte("/c.html"),
},
"b2.html": &fstest.MapFile{
Data: []byte("/c.html"),
},
"c.html": &fstest.MapFile{
Data: []byte("/"),
},
})))
defer srv.Close()
cl := srv.Client()
// Task fetches a page and extracts the URLs
task := func(u string) ([]string, error) {
res, err := cl.Get(srv.URL + u)
if err != nil {
return nil, err
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
return nil, err
}
return strings.Split(string(body), "\n"), nil
}
// Manager keeps track of which pages have been visited and the results graph
tried := map[string]int{}
results := map[string][]string{}
manager := func(req string, urls []string, err error) ([]string, error) {
if err != nil {
// If there's a problem fetching a page, try three times
if tried[req] < 3 {
tried[req]++
return []string{req}, nil
}
return nil, err
}
results[req] = urls
var newurls []string
for _, u := range urls {
if tried[u] == 0 {
newurls = append(newurls, u)
tried[u]++
}
}
return newurls, nil
}
// Process the tasks with as many workers as GOMAXPROCS
err := workgroup.Do(workgroup.MaxProcs, task, manager, "/")
if err != nil {
fmt.Println("error", err)
}
keys := maps.Keys(results)
slices.Sort(keys)
for _, key := range keys {
fmt.Println(key, "links to:")
for _, v := range results[key] {
fmt.Println("- ", v)
}
}
// Output:
// / links to:
// - /a.html
// /a.html links to:
// - /b1.html
// - /b2.html
// /b1.html links to:
// - /c.html
// /b2.html links to:
// - /c.html
// /c.html links to:
// - /
}
func ExampleDoTasks() {
times := []time.Duration{
50 * time.Millisecond,
100 * time.Millisecond,
200 * time.Millisecond,
}
start := time.Now()
err := workgroup.DoTasks(3, times, func(d time.Duration) error {
time.Sleep(d)
fmt.Println("slept", d)
return nil
})
if err != nil {
fmt.Println("error", err)
}
fmt.Println("executed concurrently?", time.Since(start) < 300*time.Millisecond)
// Output:
// slept 50ms
// slept 100ms
// slept 200ms
// executed concurrently? true
}
func ExampleDoFuncs() {
start := time.Now()
err := workgroup.DoFuncs(3, func() error {
time.Sleep(50 * time.Millisecond)
fmt.Println("hello")
return nil
}, func() error {
time.Sleep(100 * time.Millisecond)
fmt.Println("world")
return nil
}, func() error {
time.Sleep(200 * time.Millisecond)
fmt.Println("from workgroup.DoFuncs")
return nil
})
if err != nil {
fmt.Println("error", err)
}
fmt.Println("executed concurrently?", time.Since(start) < 300*time.Millisecond)
// Output:
// hello
// world
// from workgroup.DoFuncs
// executed concurrently? true
}
func ExampleDoTasks_cancel() {
// To cancel execution early, communicate via a context.CancelFunc
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
times := []time.Duration{
50 * time.Millisecond,
100 * time.Millisecond,
300 * time.Millisecond,
}
task := func(d time.Duration) error {
// simulate doing some work with a context
t := time.NewTimer(d)
defer t.Stop()
select {
case <-t.C:
fmt.Println("slept", d)
case <-ctx.Done():
fmt.Println("canceled")
}
// if some condition applies, cancel the context for everyone
if d == 100*time.Millisecond {
cancel()
}
return nil
}
start := time.Now()
if err := workgroup.DoTasks(3, times, task); err != nil {
fmt.Println("error", err)
}
fmt.Println("exited promptly?", time.Since(start) < 150*time.Millisecond)
// Output:
// slept 50ms
// slept 100ms
// canceled
// exited promptly? true
}