package main import ( "context" "fmt" "time" ) func worker(ctx context.Context, id int) { fmt.Printf("Worker %d: Starting ", id) defer fmt.Printf("Worker %d: Exiting ", id) for { select { case <-ctx.Done(): // Context was cancelled, time to stop fmt.Printf("Worker %d: Context cancelled, stopping gracefully. ", id) return case <-time.After(1 * time.Second): // Simulate doing some work fmt.Printf("Worker %d: Doing work... ", id) } } } func main() { // Create a context that can be cancelled ctx, cancel := context.WithCancel(context.Background()) // Start a few workers for i := 1; i <= 3; i++ { go worker(ctx, i) } fmt.Println("Main: Workers started. Waiting for 5 seconds...") time.Sleep(5 * time.Second) // Signal all workers to stop fmt.Println("Main: Sending cancellation signal...") cancel() // Give workers some time to clean up and exit time.Sleep(2 * time.Second) fmt.Println("Main: All workers should have stopped.") }