Исходники и презентации
This commit is contained in:
5
lessons/contexts/errgroup_with_ctx/go.mod
Normal file
5
lessons/contexts/errgroup_with_ctx/go.mod
Normal file
@ -0,0 +1,5 @@
|
||||
module errgroup
|
||||
|
||||
go 1.20
|
||||
|
||||
require golang.org/x/sync v0.6.0
|
||||
2
lessons/contexts/errgroup_with_ctx/go.sum
Normal file
2
lessons/contexts/errgroup_with_ctx/go.sum
Normal file
@ -0,0 +1,2 @@
|
||||
golang.org/x/sync v0.6.0 h1:5BMeUDZ7vkXGfEr1x9B4bRcTH4lpkTkpdh0T/J+qjbQ=
|
||||
golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
39
lessons/contexts/errgroup_with_ctx/main.go
Normal file
39
lessons/contexts/errgroup_with_ctx/main.go
Normal file
@ -0,0 +1,39 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"time"
|
||||
|
||||
"golang.org/x/sync/errgroup"
|
||||
)
|
||||
|
||||
func main() {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
group, groupCtx := errgroup.WithContext(ctx)
|
||||
for i := 0; i < 10; i++ {
|
||||
group.Go(func() error {
|
||||
timeout := time.Second * time.Duration(rand.Intn(10))
|
||||
|
||||
timer := time.NewTimer(timeout)
|
||||
defer timer.Stop()
|
||||
|
||||
select {
|
||||
case <-timer.C:
|
||||
fmt.Println("timeout")
|
||||
return errors.New("error")
|
||||
case <-groupCtx.Done():
|
||||
fmt.Println("canceled")
|
||||
return nil
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
if err := group.Wait(); err != nil {
|
||||
fmt.Println(err.Error())
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user