add ch14
This commit is contained in:
36
ch14/2/ch14_2.go
Normal file
36
ch14/2/ch14_2.go
Normal 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{}))
|
||||
}
|
||||
3
ch14/2/go.mod
Normal file
3
ch14/2/go.mod
Normal file
@@ -0,0 +1,3 @@
|
||||
module gitea.local.lab/Lbenedar/learning_go/ch14/2
|
||||
|
||||
go 1.25.0
|
||||
Reference in New Issue
Block a user