Skip to content

Commit

Permalink
Added example of context on golang
Browse files Browse the repository at this point in the history
  • Loading branch information
k8s4 committed Oct 16, 2024
1 parent 552a03c commit f9f5ac8
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions examples/golang/cource/05h_context.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package main

import (
"fmt"
"context"
"time"
)

func sendData(ctx context.Context, num int) {
timer := time.NewTimer(time.Duration(num) * time.Second)

select {
case <-ctx.Done():
fmt.Printf("Gorutine $%v canceled\n", num)
return
case <-timer.C:
fmt.Printf("Data was send by #%v\n", num)
}
}

func main() {
ctx := context.Background()

// ctxtype, cancel := context.WithCancel(ctx)
ctxtype, _ := context.WithTimeout(ctx, 2 * time.Second)


for i := 1; i < 6; i++ {
go sendData(ctxtype, i)
}

// time.Sleep(2 * time.Second)
// cancel()
time.Sleep(1 * time.Second)
}

0 comments on commit f9f5ac8

Please sign in to comment.