package main import ( "context" "fmt" "time" ) func main() { // create a new context with timeout of 1 second ctx, cancel := context.WithTimeout(context.Background(), time.Second*1) defer cancel() // cancel context upon function return select { // wait for context cancellation case <-ctx.Done(): fmt.Println("context canceled") // do some work until context is canceled case <-time.After(time.Millisecond * 500): fmt.Println("work done") } }
package main import ( "context" "fmt" "time" ) func worker(ctx context.Context) { for { select { // wait for context cancellation case <-ctx.Done(): fmt.Println("worker stopped") return // do some work until context is canceled default: fmt.Println("working") time.Sleep(time.Millisecond * 250) } } } func main() { // create a new context with cancel function ctx, cancel := context.WithCancel(context.Background()) defer cancel() // cancel context upon function return // start worker in separate goroutine go worker(ctx) // wait for context cancellation time.Sleep(time.Second * 1) cancel() fmt.Println("canceled") }In this example, a worker function is started in a separate goroutine that does some work until the context is cancelled. The main function sleeps for 1 second and then cancels the context, causing the worker to stop. The output would be "working" every 250 milliseconds until the context is cancelled, then "worker stopped" and "canceled".