-
-
Notifications
You must be signed in to change notification settings - Fork 56
/
group_context.go
46 lines (38 loc) 路 876 Bytes
/
group_context.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
package main
import (
"context"
"fmt"
"net/http"
"github.com/alitto/pond"
)
func main() {
// Create a worker pool
pool := pond.New(10, 1000)
defer pool.StopAndWait()
// Create a task group associated to a context
group, ctx := pool.GroupContext(context.Background())
var urls = []string{
"https://www.golang.org/",
"https://www.google.com/",
"https://www.github.com/",
}
// Submit tasks to fetch each URL
for _, url := range urls {
url := url
group.Submit(func() error {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
resp, err := http.DefaultClient.Do(req)
if err == nil {
resp.Body.Close()
}
return err
})
}
// Wait for all HTTP requests to complete.
err := group.Wait()
if err != nil {
fmt.Printf("Failed to fetch URLs: %v", err)
} else {
fmt.Println("Successfully fetched all URLs")
}
}