« Back to Index

Context package

View original Gist on GitHub

Tags: #go

golang cancel context.go

package main

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

func slow(ctx context.Context) {
	go func() {
		<-ctx.Done()
		fmt.Println("CONTEXT CANCELLED!", time.Now())
	}()
	time.Sleep(10 * time.Second)
	fmt.Println("FINISHED", time.Now())
}

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), time.Duration(5)*time.Second)
	defer cancel()

	slow(ctx)

	fmt.Println("DONE", time.Now())
}

golang parent and child contexts.go

package main

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

func main() {
	fmt.Println(createAContext())
}

func createAContext() string {
	ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
	defer cancel()
	return useTheContext(ctx)
}

func useTheContext(parentCtx context.Context) string {
	// fmt.Println("sleeping long enough for parentCtx timeout to be reached")
	// time.Sleep(2 * time.Second)
	select {
	case <-parentCtx.Done():
		fmt.Println("Context canceled before doing stuff 1")
		return "canceled"
	default:
		childCtx, cancel := context.WithCancel(parentCtx)
		cancel()
		useChildContext(childCtx, parentCtx)
		return "done"
	}
}

func useChildContext(childCtx, parentCtx context.Context) {
	select {
	case <-parentCtx.Done():
		fmt.Println("Parent context cancelled")
	case <-childCtx.Done():
		fmt.Println("Child context cancelled")
	default:
		fmt.Printf("using child context: %#v\n", childCtx)
	}
}