Skip to content

Instantly share code, notes, and snippets.

@atreya2011
Created November 3, 2020 08:02
Show Gist options
  • Save atreya2011/77f26bf35d3648da826b85c7af30eb9c to your computer and use it in GitHub Desktop.
Save atreya2011/77f26bf35d3648da826b85c7af30eb9c to your computer and use it in GitHub Desktop.
Go Context Example
package main
import (
"context"
"fmt"
"time"
)
func main() {
ctx := context.Background()
go parentProcess(ctx)
time.Sleep(1000 * time.Second)
}
func parentProcess(ctx context.Context) {
childCtx, cancel := context.WithCancel(ctx)
childCtx2, _ := context.WithCancel(childCtx)
go childProcess(childCtx, "child1")
go childProcess(childCtx2, "child2")
// Cancel after 10 seconds
time.Sleep(10 * time.Second)
// childCtx2, which is derived from childCtx, also propagates the cancellation. childCtx2's cancelFunc must be called as well otherwise go vet yells at us
cancel()
// cancel after 10 seconds. cancelFunc is not called in this sample, but you have to explicitly call cancelFunc somewhere otherwise go vet yells at us
ctxWithTimeout10, _ := context.WithTimeout(ctx, time.Second*10)
go childProcess(ctxWithTimeout10, "with timeout")
}
func childProcess(ctx context.Context, prefix string) {
for i := 1; i <= 1000; i++ {
select {
case <-ctx.Done():
fmt.Printf("%s: canceld \n", prefix)
return
case <-time.After(1 * time.Second):
fmt.Printf("%s:%d sec..\n", prefix, i)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment