Исходники и презентации
This commit is contained in:
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