package main import ( "context" "fmt" "time" ) func main() { parentCtx, cancelFunc := context.WithTimeout(context.Background(), 5*time.Second) defer cancelFunc() childCtx, _ := context.WithCancel(parentCtx) go func(ctx context.Context) { select { case <-time.After(10 * time.Second): fmt.Println("finished") case <-ctx.Done(): fmt.Println("cancelled") } }(childCtx) <-parentCtx.Done() fmt.Println("parent context cancelled") }
package main import ( "context" "fmt" "time" ) func main() { ctx, cancelFunc := context.WithCancel(context.Background()) go func() { select { case <-time.After(5 * time.Second): fmt.Println("goroutine 1 finished") case <-ctx.Done(): fmt.Println("goroutine 1 cancelled") } }() go func() { select { case <-time.After(7 * time.Second): fmt.Println("goroutine 2 finished") case <-ctx.Done(): fmt.Println("goroutine 2 cancelled") } }() cancelFunc() <-ctx.Done() fmt.Println("context cancelled") }Package: context