Context Cancel & Timeout

Manual cancellation and automatic timeout with context.

package main

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

func worker(ctx context.Context, id int, done chan<- struct{}) {
	defer func() { done <- struct{}{} }()
	select {
	case <-ctx.Done():
		fmt.Printf("worker %d cancelled: %v\n", id, ctx.Err())
	case <-time.After(5 * time.Second):
		fmt.Printf("worker %d finished\n", id)
	}
}

func main() {
	done := make(chan struct{}, 1)

	// Manual cancel
	fmt.Println("--- WithCancel ---")
	ctx1, cancel1 := context.WithCancel(context.Background())
	go worker(ctx1, 1, done)
	cancel1()
	<-done // wait for goroutine to finish

	// Timeout
	fmt.Println("--- WithTimeout ---")
	ctx2, cancel2 := context.WithTimeout(context.Background(), 300*time.Millisecond)
	defer cancel2()
	go worker(ctx2, 2, done)
	<-done // wait for goroutine to finish

	// Parent cancels children
	fmt.Println("--- Parent/Child ---")
	parent, cancelParent := context.WithCancel(context.Background())
	child, cancelChild := context.WithCancel(parent)
	defer cancelChild()
	go worker(child, 3, done)
	cancelParent() // cancels child too
	<-done // wait for goroutine to finish
}
▶ Open Go Playground

Copy the code above and paste to run

© 2026 ByteLearn.dev. Free courses for developers. · Privacy