Golang 标准库 - 示例代码

context

Golang 标准库 - context

context 包定义了上下文类型,用于在 API 边界和 goroutine 之间传递截止时间、取消信号和请求范围的值。所有长时间运行、可能被取消的操作,都应当接收一个 context.Context 作为第一个参数。

核心 API 速查

函数 用途 返回
context.Background() 根 context,永不取消 Context
context.TODO() 占位,表示「还没想好用哪个」 Context
context.WithCancel(parent) 手动取消 Context, cancel
context.WithTimeout(parent, d) 相对超时 Context, cancel
context.WithDeadline(parent, t) 绝对截止时间 Context, cancel
context.WithValue(parent, k, v) 传请求范围的值 Context

黄金法则:cancel 函数即使 context 没超时也要 defer cancel(),否则会泄漏资源。

可运行示例

package main

import (
	"context"
	"fmt"
	"time"
)

func longRunningProcess(ctx context.Context, id int) {
	for i := 0; i < 10; i++ {
		select {
		case <-ctx.Done():
			fmt.Printf("Process %d: cancelled: %v\n", id, ctx.Err())
			return
		default:
			fmt.Printf("Process %d: step %d\n", id, i)
			time.Sleep(300 * time.Millisecond)
		}
	}
	fmt.Printf("Process %d: completed\n", id)
}

func main() {
	// 1. WithCancel:手动取消
	fmt.Println("=== WithCancel ===")
	ctx, cancel := context.WithCancel(context.Background())
	go longRunningProcess(ctx, 1)
	time.Sleep(1 * time.Second)
	cancel() // 取消所有派生的 goroutine
	time.Sleep(500 * time.Millisecond)

	// 2. WithTimeout:相对超时
	fmt.Println("\n=== WithTimeout ===")
	ctx2, cancel2 := context.WithTimeout(context.Background(), 2*time.Second)
	defer cancel2()

	done := make(chan bool)
	go func() {
		longRunningProcess(ctx2, 2)
		done <- true
	}()

	select {
	case <-done:
		fmt.Println("Process completed")
	case <-ctx2.Done():
		fmt.Println("Timeout:", ctx2.Err())
	}

	// 3. WithDeadline:绝对截止时间
	fmt.Println("\n=== WithDeadline ===")
	deadline := time.Now().Add(1 * time.Second)
	ctx3, cancel3 := context.WithDeadline(context.Background(), deadline)
	defer cancel3()

	go longRunningProcess(ctx3, 3)

	select {
	case <-ctx3.Done():
		fmt.Println("Deadline reached:", ctx3.Err())
	case <-time.After(3 * time.Second):
		fmt.Println("Waited too long")
	}

	// 4. WithValue:传请求范围的值(注意:只传请求级元数据,不传业务参数)
	fmt.Println("\n=== WithValue ===")
	type ctxKey string
	const userIDKey ctxKey = "userID"
	ctx4 := context.WithValue(context.Background(), userIDKey, "12345")
	if v, ok := ctx4.Value(userIDKey).(string); ok {
		fmt.Println("User ID:", v)
	}
}

站内深度阅读(原理篇)

会用 WithTimeout 只是入门,真正拉开差距的是理解 context 的取消树是如何传播的:

context 的取消信号本质是「关闭一个 channel」,建议搭配 Go Channel 底层实现全解析 理解 close(chan) 的广播唤醒语义。

相关阅读

🛒 站长推荐(京东联盟)

以上链接含京东联盟推广代码;通过链接购买本站可能获得少量佣金,不影响你的购买价格。

📮 关注公众号「Go2AI之路」
Go2AI之路 公众号二维码

每周更新 Go + AI 应用开发实战:AI 面试官完整项目、MCP、Agent 工程化,完整源码随文章首发。

微信扫码,或搜索「Go2AI之路」关注,第一时间获取系列更新与源码,不再错过任何一篇。

如有疑问关注公众号给我留言
wx

关注公众号

©2017-2026 鲁ICP备17023316号-1 Powered by Hugo · 隐私政策