This commit is contained in:
lbenedar
2026-02-23 16:56:00 +03:00
parent 1f4ba997b7
commit 589d2ae3d8
6 changed files with 136 additions and 0 deletions

36
ch14/2/ch14_2.go Normal file
View File

@@ -0,0 +1,36 @@
package main
import (
"context"
"fmt"
"math/rand"
"time"
)
type RandSum struct{}
func main() {
sum := 0
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(2)*time.Second)
defer cancel()
start := time.Now()
i := 0
outLoop:
for {
select {
case <-ctx.Done():
ctx = context.WithValue(ctx, RandSum{}, "timeout")
break outLoop
default:
i++
randNum := rand.Int() % 100_000_000
//fmt.Printf("Randnum is %d\n", randNum)
sum = sum + randNum
if randNum == 1234 {
ctx = context.WithValue(ctx, RandSum{}, "number reached")
break outLoop
}
}
}
fmt.Printf("Sum is %d after %v; iterations - %d; cause - %s\n", sum, time.Since(start), i, ctx.Value(RandSum{}))
}