From d0faf0a1f2802ed9fbcc318ad325c7c674175b51 Mon Sep 17 00:00:00 2001 From: hthuz Date: Thu, 4 Jul 2024 23:57:07 +0800 Subject: [PATCH] add: go context --- go/context/context.go | 32 +++++++++++++++++++++++++++++++ go/contextCancel/contextCancel.go | 31 ++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+) create mode 100644 go/context/context.go create mode 100644 go/contextCancel/contextCancel.go diff --git a/go/context/context.go b/go/context/context.go new file mode 100644 index 0000000..5f039ed --- /dev/null +++ b/go/context/context.go @@ -0,0 +1,32 @@ +package main + +import ( + "context" + "fmt" + "time" +) + +func main() { + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + + go performTask(ctx) + + select { + case <-ctx.Done(): + fmt.Printf("%T\n", ctx) + fmt.Println(ctx) + fmt.Printf("%T\n", ctx.Done()) + fmt.Println(ctx.Done()) + fmt.Println("Task timeout") + } +} + +// If performTask is not finished within 2 seconds, the program terminates +func performTask(ctx context.Context) { + select { + case <-time.After(5 * time.Second): + fmt.Println("Task completed") + } + +} diff --git a/go/contextCancel/contextCancel.go b/go/contextCancel/contextCancel.go new file mode 100644 index 0000000..db72a17 --- /dev/null +++ b/go/contextCancel/contextCancel.go @@ -0,0 +1,31 @@ +package main + +import ( + "context" + "fmt" + "time" +) + +func main() { + ctx, cancel := context.WithCancel(context.Background()) + + go task(ctx) + + time.Sleep(2 * time.Second) + cancel() + time.Sleep(1 * time.Second) +} + +func task(ctx context.Context) { + for { + select { + case <-ctx.Done(): + fmt.Println("Task terminated") + return + default: + fmt.Println("Doing task") + time.Sleep(300 * time.Millisecond) + } + } + +}