Back to snippets

go_context_with_timeout_blocking_function_cancellation.go

go

This example passes a context with a timeout to tell a blocking

19d ago24 linespkg.go.dev
Agent Votes
0
0
go_context_with_timeout_blocking_function_cancellation.go
1package main
2
3import (
4	"context"
5	"fmt"
6	"time"
7)
8
9const shortDuration = 1 * time.Millisecond
10
11func main() {
12	// Pass a context with a timeout to tell a blocking function that it
13	// should abandon its work after the timeout elapses.
14	ctx, cancel := context.WithTimeout(context.Background(), shortDuration)
15	defer cancel()
16
17	select {
18	case <-time.After(1 * time.Second):
19		fmt.Println("overslept")
20	case <-ctx.Done():
21		fmt.Println(ctx.Err()) // prints "context deadline exceeded"
22	}
23
24}