-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
56 lines (49 loc) · 1.22 KB
/
main.go
File metadata and controls
56 lines (49 loc) · 1.22 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
package main
import (
"context"
"fmt"
"time"
"golang.org/x/sync/errgroup"
)
func main() {
// Create an errgroup with a context.
// If any goroutine returns an error, 'ctx' will be cancelled.
g, ctx := errgroup.WithContext(context.Background())
// Task 1: Successful task
g.Go(func() error {
// Simulate work
select {
case <-time.After(1 * time.Second):
fmt.Println("Task 1 completed")
return nil
case <-ctx.Done():
fmt.Println("Task 1 cancelled")
return ctx.Err()
}
})
// Task 2: Failing task
g.Go(func() error {
// Simulate a quick failure
time.Sleep(100 * time.Millisecond)
return fmt.Errorf("Task 2 failed critically!")
})
// Task 3: Another task (will be cancelled because Task 2 fails)
g.Go(func() error {
select {
case <-time.After(2 * time.Second):
fmt.Println("Task 3 completed")
return nil
case <-ctx.Done():
// This happens because Task 2 failed
fmt.Println("Task 3 cancelled because sibling failed")
return ctx.Err()
}
})
// Wait for all to finish.
// Returns the first error encountered (from Task 2).
if err := g.Wait(); err != nil {
fmt.Printf("Outcome: The group operation failed: %v\n", err)
} else {
fmt.Println("Outcome: All tasks succeeded!")
}
}