go / intermediate
Snippet
Managing Lifecycle and Cancellation with Context
Go's context package enables structured cancellation signals and deadlines to propagate across API boundaries and goroutines. Using a context prevents resource leaks by cleanly notifying background tasks to stop processing once their parent operation times out or is cancelled.
snippet.go
go
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
package mainimport ("context""fmt""time")func worker(ctx context.Context) {for {select {case <-ctx.Done():fmt.Println("Worker stopped:", ctx.Err())returndefault:fmt.Println("Working...")time.Sleep(500 * time.Millisecond)}}}func main() {ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)defer cancel()go worker(ctx)time.Sleep(3 * time.Second)}
Breakdown
1
context.WithTimeout(context.Background(), 2*time.Second)
Creates a derived context that automatically sends a cancellation signal via its Done channel after 2 seconds.
2
defer cancel()
Ensures that the context's internal resources are cleaned up immediately when main exits, preventing memory leaks.
3
case <-ctx.Done():
Monitors the cancellation signal, unblocking the worker loop as soon as the timeout occurs or cancel is explicitly called.
4
ctx.Err()
Returns the reason for context termination, such as context.DeadlineExceeded or context.Canceled.