-
Notifications
You must be signed in to change notification settings - Fork 0
/
errgroup-basics-3.go
54 lines (50 loc) · 1.06 KB
/
errgroup-basics-3.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 main
import (
"context"
"fmt"
"log"
"net/http"
"time"
"golang.org/x/sync/errgroup"
)
/*
errgroup.WithContext() function creates a new group of goroutines of the errgroup.Group type and a new context.Context,
which can be passed between goroutines and will allow canceling the execution of the task group.
*/
func egrpPattern3() {
eg, ctx := errgroup.WithContext(context.Background())
eg.Go(func() error {
for {
select {
case <-ctx.Done():
log.Printf("goroutine 1 should cancel")
return nil
default:
fmt.Println("task executing")
if _, err := http.Get("hts://blog.kennycoder.io"); err != nil {
return err
}
time.Sleep(1 * time.Second)
}
}
})
eg.Go(func() error {
for i := 0; i < 10; i++ {
select {
case <-ctx.Done():
log.Printf("goroutine 2 should cancel")
return nil
default:
_, err := http.Get("https://google.com")
if err != nil {
return err
}
time.Sleep(6 * time.Second)
}
}
return nil
})
if err := eg.Wait(); err != nil {
log.Fatalf("get error: %v", err)
}
}