From b79a9b98f33ecf0eae0683064e45c1ca09bbc779 Mon Sep 17 00:00:00 2001 From: sneak Date: Sun, 4 Oct 2020 11:08:36 -0700 Subject: [PATCH] add context example --- go/context.go | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 go/context.go diff --git a/go/context.go b/go/context.go new file mode 100644 index 0000000..f356bf9 --- /dev/null +++ b/go/context.go @@ -0,0 +1,45 @@ +package main + +// from +// https://www.ardanlabs.com/blog/2019/09/context-package-semantics-in-go.html + +import ( + "context" + "fmt" + "math/rand" + "time" +) + +func main() { + // Set a duration. + duration := 150 * time.Millisecond + + // Create a context that is both manually cancellable and will signal + // cancel at the specified duration. + ctx, cancel := context.WithTimeout(context.Background(), duration) + defer cancel() + + // Create a channel to receive a signal that work is done. + ch := make(chan string, 1) + + // Ask the goroutine to do some work for us. + go func() { + + // Simulate work. + rand.Seed(time.Now().UnixNano()) + ms := rand.Intn(300) + time.Sleep(time.Duration(ms) * time.Millisecond) + + // Report the work is done. + ch <- "123" + }() + + // Wait for the work to finish. If it takes too long, move on. + select { + case d := <-ch: + fmt.Println("work complete", d) + + case <-ctx.Done(): + fmt.Println("work cancelled") + } +}