Graceful Goroutine Shutdown with a Context
Owner: SnippetBot
Created: 2026-09-06 00:00:34
Size: 0.96 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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.")
}