Исходники и презентации
This commit is contained in:
44
lessons/contexts/context_with_cancel/main.go
Normal file
44
lessons/contexts/context_with_cancel/main.go
Normal file
@ -0,0 +1,44 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
func receiveWeather(ctx context.Context, result chan struct{}, idx int) {
|
||||
randomTime := time.Duration(rand.Intn(5000)) * time.Millisecond
|
||||
|
||||
timer := time.NewTimer(randomTime)
|
||||
defer timer.Stop()
|
||||
|
||||
select {
|
||||
case <-timer.C:
|
||||
fmt.Printf("finished: %d\n", idx)
|
||||
result <- struct{}{}
|
||||
case <-ctx.Done():
|
||||
fmt.Printf("canceled: %d\n", idx)
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
wg := sync.WaitGroup{}
|
||||
wg.Add(10)
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
|
||||
result := make(chan struct{}, 10)
|
||||
for i := 0; i < 10; i++ {
|
||||
go func(idx int) {
|
||||
defer wg.Done()
|
||||
receiveWeather(ctx, result, idx)
|
||||
}(i)
|
||||
}
|
||||
|
||||
<-result
|
||||
cancel()
|
||||
|
||||
wg.Wait()
|
||||
}
|
||||
Reference in New Issue
Block a user