{"id":10021331,"date":"2026-03-30T15:40:15","date_gmt":"2026-03-30T07:40:15","guid":{"rendered":"https:\/\/itmax.cn\/?p=10021331"},"modified":"2026-03-30T15:40:15","modified_gmt":"2026-03-30T07:40:15","slug":"%e6%b7%b1%e5%85%a5%e7%90%86%e8%a7%a3-go-context%ef%bc%9a%e4%bb%8e%e5%8e%9f%e7%90%86%e5%88%b0%e5%ae%9e%e6%88%98%ef%bc%88%e5%9f%ba%e4%ba%8e-go-1-26%ef%bc%89","status":"publish","type":"post","link":"https:\/\/itmax.cn\/?p=10021331","title":{"rendered":"\u6df1\u5165\u7406\u89e3 Go Context\uff1a\u4ece\u539f\u7406\u5230\u5b9e\u6218\uff08\u57fa\u4e8e Go 1.26\uff09"},"content":{"rendered":"<h2>\u524d\u8a00<\/h2>\n<p>\u5728 Go \u7684\u5e76\u53d1\u7f16\u7a0b\u4e2d\uff0c<code>context<\/code> \u5305\u662f\u6700\u6838\u5fc3\u7684\u57fa\u7840\u8bbe\u65bd\u4e4b\u4e00\u3002\u5b83\u89e3\u51b3\u4e86\u4e00\u4e2a\u770b\u4f3c\u7b80\u5355\u5374\u6781\u5176\u91cd\u8981\u7684\u95ee\u9898\uff1a<strong>\u5982\u4f55\u4f18\u96c5\u5730\u63a7\u5236 goroutine \u7684\u751f\u547d\u5468\u671f\uff1f<\/strong><\/p>\n<p>\u5148\u770b\u4e00\u4e2a\u6ca1\u6709 context \u7684\u53cd\u9762\u4f8b\u5b50\uff1a<\/p>\n<pre><code class=\"go\">\/\/ \u6a21\u62df\uff1a\u7528\u6237\u8bf7\u6c42\u4e00\u4e2a\u63a5\u53e3\uff0c\u540e\u7aef\u6d3e goroutine \u53bb\u67e5\u6570\u636e\u5e93\nfunc handleRequest() {\n    go queryDB(&quot;SELECT * FROM orders&quot;) \/\/ \u8017\u65f6 5 \u79d2\n    go callRPC(&quot;user-service&quot;)         \/\/ \u8017\u65f6 3 \u79d2\n    go fetchCache(&quot;hot-items&quot;)         \/\/ \u8017\u65f6 1 \u79d2\n}<\/code><\/pre>\n<p>\u5982\u679c\u7528\u6237\u5728\u7b2c 0.5 \u79d2\u5c31\u65ad\u5f00\u4e86\u8fde\u63a5\uff0c\u4f1a\u53d1\u751f\u4ec0\u4e48\uff1f<\/p>\n<pre><code class=\"go\">func main() {\n    for i := 0; i &lt; 100; i++ {\n        handleRequest() \/\/ \u6bcf\u4e2a\u8bf7\u6c42\u6d3e\u751f 3 \u4e2a goroutine\n        \/\/ \u5047\u8bbe\u7528\u6237\u5168\u90e8\u5728 0.5 \u79d2\u540e\u65ad\u5f00\n    }\n    time.Sleep(1 * time.Second)\n    fmt.Println(&quot;\u5f53\u524d goroutine \u6570:&quot;, runtime.NumGoroutine())\n    \/\/ \u8f93\u51fa: \u5f53\u524d goroutine \u6570: 301\n    \/\/ 300 \u4e2a goroutine \u5728\u505a\u65e0\u7528\u529f\uff0c\u6ca1\u4eba\u8981\u5b83\u4eec\u7684\u7ed3\u679c\u4e86\n}<\/code><\/pre>\n<p>\u8fd9 300 \u4e2a goroutine \u6bcf\u4e00\u4e2a\u90fd\u5728\u5360\u7528\u5185\u5b58\uff08\u6700\u5c11 2KB \u6808\u7a7a\u95f4\uff09\u3001\u53ef\u80fd\u6301\u6709\u6570\u636e\u5e93\u8fde\u63a5\u3001\u6d88\u8017 CPU \u65f6\u95f4\u7247\u2014\u2014\u800c\u5b83\u4eec\u7684\u7ed3\u679c\u5df2\u7ecf\u6ca1\u4eba\u9700\u8981\u4e86\u3002\u5728\u9ad8\u5e76\u53d1\u573a\u666f\u4e0b\uff0c\u8fd9\u79cd\u6cc4\u6f0f\u4f1a\u50cf\u6eda\u96ea\u7403\u4e00\u6837\u62d6\u57ae\u6574\u4e2a\u670d\u52a1\u3002<\/p>\n<p>\u6709\u4e86 context\uff0c\u4e00\u884c\u4ee3\u7801\u5c31\u80fd\u89e3\u51b3\uff1a<\/p>\n<pre><code class=\"go\">func handleRequest(ctx context.Context) {\n    go queryDB(ctx, &quot;SELECT * FROM orders&quot;)\n    go callRPC(ctx, &quot;user-service&quot;)\n    go fetchCache(ctx, &quot;hot-items&quot;)\n}\n\n\/\/ \u7528\u6237\u65ad\u5f00 \u2192 ctx \u88ab\u53d6\u6d88 \u2192 \u4e09\u4e2a goroutine \u6536\u5230\u4fe1\u53f7 \u2192 \u7acb\u5373\u9000\u51fa\n\/\/ goroutine \u6570: 1\uff08\u53ea\u5269 main\uff09<\/code><\/pre>\n<p>\u8fd9\u5c31\u662f context \u7684\u4ef7\u503c\uff1a<strong>\u5b83\u662f goroutine \u4e4b\u95f4\u7684&#8221;\u7d27\u6025\u53eb\u505c&#8221;\u673a\u5236<\/strong>\u3002\u6ca1\u6709\u5b83\uff0c\u4f60\u6d3e\u51fa\u53bb\u7684 goroutine \u5c31\u50cf\u65ad\u4e86\u7ebf\u7684\u98ce\u7b5d\uff0c\u518d\u4e5f\u6536\u4e0d\u56de\u6765\u3002<\/p>\n<h2>\u4e00\u3001Context \u662f\u4ec0\u4e48<\/h2>\n<p><code>context.Context<\/code> \u662f\u4e00\u4e2a\u63a5\u53e3\uff0c\u5b9a\u4e49\u5728\u6807\u51c6\u5e93 <code>context<\/code> \u5305\u4e2d\uff1a<\/p>\n<pre><code class=\"go\">type Context interface {\n    \/\/ \u8fd4\u56de context \u7684\u622a\u6b62\u65f6\u95f4\u3002\u5982\u679c\u6ca1\u6709\u8bbe\u7f6e\u622a\u6b62\u65f6\u95f4\uff0cok \u4e3a false\n    Deadline() (deadline time.Time, ok bool)\n\n    \/\/ \u8fd4\u56de\u4e00\u4e2a channel\uff0c\u5f53 context \u88ab\u53d6\u6d88\u6216\u8d85\u65f6\u65f6\uff0c\u8be5 channel \u4f1a\u88ab\u5173\u95ed\n    Done() &lt;-chan struct{}\n\n    \/\/ \u8fd4\u56de context \u88ab\u53d6\u6d88\u7684\u539f\u56e0\n    Err() error\n\n    \/\/ \u4ece context \u4e2d\u83b7\u53d6 key \u5bf9\u5e94\u7684\u503c\n    Value(key any) any\n}<\/code><\/pre>\n<p>\u56db\u4e2a\u65b9\u6cd5\uff0c\u5404\u53f8\u5176\u804c\uff1a<\/p>\n<table>\n<thead>\n<tr>\n<th>\u65b9\u6cd5<\/th>\n<th>\u4f5c\u7528<\/th>\n<th>\u5178\u578b\u4f7f\u7528\u573a\u666f<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td><code>Deadline()<\/code><\/td>\n<td>\u83b7\u53d6\u622a\u6b62\u65f6\u95f4<\/td>\n<td>\u5224\u65ad\u5269\u4f59\u65f6\u95f4\u662f\u5426\u591f\u5b8c\u6210\u64cd\u4f5c<\/td>\n<\/tr>\n<tr>\n<td><code>Done()<\/code><\/td>\n<td>\u83b7\u53d6\u53d6\u6d88\u4fe1\u53f7 channel<\/td>\n<td>\u5728 select \u4e2d\u76d1\u542c\u53d6\u6d88\u4e8b\u4ef6<\/td>\n<\/tr>\n<tr>\n<td><code>Err()<\/code><\/td>\n<td>\u83b7\u53d6\u53d6\u6d88\u539f\u56e0<\/td>\n<td>\u533a\u5206\u662f\u4e3b\u52a8\u53d6\u6d88\u8fd8\u662f\u8d85\u65f6<\/td>\n<\/tr>\n<tr>\n<td><code>Value()<\/code><\/td>\n<td>\u83b7\u53d6\u4f20\u9012\u7684\u503c<\/td>\n<td>\u8bfb\u53d6 request-scoped \u6570\u636e\uff08\u5982 traceID\uff09<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h2>\u4e8c\u3001\u4e94\u79cd\u521b\u5efa\u65b9\u5f0f<\/h2>\n<h3>1. context.Background() \u548c context.TODO()<\/h3>\n<p>\u8fd9\u4e24\u4e2a\u51fd\u6570\u8fd4\u56de\u7684\u90fd\u662f\u7a7a context\uff0c\u6c38\u8fdc\u4e0d\u4f1a\u88ab\u53d6\u6d88\uff0c\u6ca1\u6709\u622a\u6b62\u65f6\u95f4\uff0c\u6ca1\u6709\u503c\u3002<\/p>\n<pre><code class=\"go\">\/\/ \u4f5c\u4e3a\u6574\u68f5 context \u6811\u7684\u6839\u8282\u70b9\uff0c\u901a\u5e38\u5728 main\u3001init \u6216\u9876\u5c42\u8bf7\u6c42\u5165\u53e3\u4f7f\u7528\nctx := context.Background()\n\n\/\/ \u5f53\u4f60\u8fd8\u4e0d\u786e\u5b9a\u8be5\u7528\u4ec0\u4e48 context \u65f6\u7684\u5360\u4f4d\u7b26\nctx := context.TODO()<\/code><\/pre>\n<p>\u5b83\u4eec\u7684\u533a\u522b\u7eaf\u7cb9\u662f\u8bed\u4e49\u4e0a\u7684\u2014\u2014<code>TODO()<\/code> \u662f\u5728\u544a\u8bc9\u4ee3\u7801\u7684\u8bfb\u8005\uff1a&#8221;\u8fd9\u91cc\u4ee5\u540e\u8981\u6362\u6210\u771f\u6b63\u7684 context&#8221;\u3002<\/p>\n<h3>2. context.WithCancel \u2014 \u624b\u52a8\u53d6\u6d88<\/h3>\n<pre><code class=\"go\">func WithCancel(parent Context) (ctx Context, cancel CancelFunc)<\/code><\/pre>\n<p>\u8fd4\u56de\u4e00\u4e2a\u5b50 context \u548c\u4e00\u4e2a\u53d6\u6d88\u51fd\u6570\u3002\u8c03\u7528 <code>cancel()<\/code> \u65f6\uff0c\u5b50 context \u7684 <code>Done()<\/code> channel \u4f1a\u88ab\u5173\u95ed\uff0c\u6240\u6709\u76d1\u542c\u5b83\u7684 goroutine \u90fd\u4f1a\u6536\u5230\u4fe1\u53f7\u3002<\/p>\n<pre><code class=\"go\">func main() {\n    ctx, cancel := context.WithCancel(context.Background())\n\n    go worker(ctx, &quot;worker-1&quot;)\n    go worker(ctx, &quot;worker-2&quot;)\n\n    time.Sleep(3 * time.Second)\n    fmt.Println(&quot;\u4e3b\u534f\u7a0b\uff1a\u901a\u77e5\u6240\u6709 worker \u505c\u6b62&quot;)\n    cancel() \/\/ \u624b\u52a8\u53d1\u51fa\u53d6\u6d88\u4fe1\u53f7\uff0c\u540c\u65f6\u91ca\u653e\u8d44\u6e90\n\n    time.Sleep(1 * time.Second) \/\/ \u7b49\u5f85 worker \u9000\u51fa\n}\n\nfunc worker(ctx context.Context, name string) {\n    for {\n        select {\n        case &lt;-ctx.Done():\n            fmt.Printf(&quot;%s: \u6536\u5230\u53d6\u6d88\u4fe1\u53f7\uff0c\u9000\u51fa\u3002\u539f\u56e0: %v\/n&quot;, name, ctx.Err())\n            return\n        default:\n            fmt.Printf(&quot;%s: \u5de5\u4f5c\u4e2d...\/n&quot;, name)\n            time.Sleep(1 * time.Second)\n        }\n    }\n}<\/code><\/pre>\n<p>\u8f93\u51fa\uff1a<\/p>\n<pre><code>worker-1: \u5de5\u4f5c\u4e2d...\nworker-2: \u5de5\u4f5c\u4e2d...\nworker-1: \u5de5\u4f5c\u4e2d...\nworker-2: \u5de5\u4f5c\u4e2d...\nworker-1: \u5de5\u4f5c\u4e2d...\nworker-2: \u5de5\u4f5c\u4e2d...\n\u4e3b\u534f\u7a0b\uff1a\u901a\u77e5\u6240\u6709 worker \u505c\u6b62\nworker-1: \u6536\u5230\u53d6\u6d88\u4fe1\u53f7\uff0c\u9000\u51fa\u3002\u539f\u56e0: context canceled\nworker-2: \u6536\u5230\u53d6\u6d88\u4fe1\u53f7\uff0c\u9000\u51fa\u3002\u539f\u56e0: context canceled<\/code><\/pre>\n<h3>3. context.WithTimeout \u2014 \u8d85\u65f6\u81ea\u52a8\u53d6\u6d88<\/h3>\n<pre><code class=\"go\">func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)<\/code><\/pre>\n<p>\u5728\u6307\u5b9a\u65f6\u95f4\u540e\u81ea\u52a8\u53d6\u6d88\u3002\u8fd9\u662f HTTP \u5ba2\u6237\u7aef\u8c03\u7528\u3001\u6570\u636e\u5e93\u67e5\u8be2\u7b49\u573a\u666f\u7684\u6807\u914d\u3002<\/p>\n<pre><code class=\"go\">func queryDatabase(ctx context.Context) (string, error) {\n    \/\/ \u6a21\u62df\u4e00\u4e2a\u53ef\u80fd\u5f88\u6162\u7684\u6570\u636e\u5e93\u67e5\u8be2\n    select {\n    case &lt;-time.After(5 * time.Second): \/\/ \u67e5\u8be2\u9700\u8981 5 \u79d2\n        return &quot;\u67e5\u8be2\u7ed3\u679c&quot;, nil\n    case &lt;-ctx.Done():\n        return &quot;&quot;, fmt.Errorf(&quot;\u67e5\u8be2\u88ab\u53d6\u6d88: %w&quot;, ctx.Err())\n    }\n}\n\nfunc main() {\n    \/\/ \u8bbe\u7f6e 2 \u79d2\u8d85\u65f6\n    ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)\n    defer cancel()\n\n    result, err := queryDatabase(ctx)\n    if err != nil {\n        fmt.Println(&quot;\u9519\u8bef:&quot;, err) \/\/ \u8f93\u51fa: \u9519\u8bef: \u67e5\u8be2\u88ab\u53d6\u6d88: context deadline exceeded\n        return\n    }\n    fmt.Println(&quot;\u7ed3\u679c:&quot;, result)\n}<\/code><\/pre>\n<h3>4. context.WithDeadline \u2014 \u6307\u5b9a\u622a\u6b62\u65f6\u95f4<\/h3>\n<pre><code class=\"go\">func WithDeadline(parent Context, d time.Time) (Context, CancelFunc)<\/code><\/pre>\n<p>\u548c <code>WithTimeout<\/code> \u7c7b\u4f3c\uff0c\u4f46\u63a5\u53d7\u7684\u662f\u4e00\u4e2a\u7edd\u5bf9\u65f6\u95f4\u70b9\u800c\u975e\u76f8\u5bf9\u65f6\u957f\u3002\u5b9e\u9645\u4e0a <code>WithTimeout<\/code> \u5185\u90e8\u5c31\u662f\u8c03\u7528\u7684 <code>WithDeadline<\/code>\uff1a<\/p>\n<pre><code class=\"go\">\/\/ \u6807\u51c6\u5e93\u6e90\u7801\nfunc WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) {\n    return WithDeadline(parent, time.Now().Add(timeout))\n}<\/code><\/pre>\n<p>\u4f7f\u7528\u573a\u666f\uff1a\u5f53\u4f60\u9700\u8981\u8ba9\u591a\u4e2a\u64cd\u4f5c\u5171\u4eab\u540c\u4e00\u4e2a\u622a\u6b62\u65f6\u95f4\u65f6\uff0c<code>WithDeadline<\/code> \u66f4\u76f4\u89c2\u3002<\/p>\n<pre><code class=\"go\">func main() {\n    deadline := time.Now().Add(3 * time.Second)\n\n    ctx, cancel := context.WithDeadline(context.Background(), deadline)\n    defer cancel()\n\n    \/\/ \u68c0\u67e5\u8fd8\u5269\u591a\u5c11\u65f6\u95f4\n    if d, ok := ctx.Deadline(); ok {\n        fmt.Printf(&quot;\u622a\u6b62\u65f6\u95f4: %v, \u5269\u4f59: %v\/n&quot;, d, time.Until(d))\n    }\n}<\/code><\/pre>\n<h3>5. context.WithValue \u2014 \u4f20\u9012\u8bf7\u6c42\u7ea7\u6570\u636e<\/h3>\n<pre><code class=\"go\">func WithValue(parent Context, key, val any) Context<\/code><\/pre>\n<p>\u5728 context \u4e2d\u9644\u52a0\u4e00\u4e2a\u952e\u503c\u5bf9\u3002\u5e38\u7528\u4e8e\u4f20\u9012 traceID\u3001\u7528\u6237\u8ba4\u8bc1\u4fe1\u606f\u7b49 request-scoped \u6570\u636e\u3002<\/p>\n<pre><code class=\"go\">\/\/ \u63a8\u8350\u4f7f\u7528\u81ea\u5b9a\u4e49\u7c7b\u578b\u4f5c\u4e3a key\uff0c\u907f\u514d\u51b2\u7a81\ntype contextKey string\n\nconst (\n    keyTraceID contextKey = &quot;traceID&quot;\n    keyUserID  contextKey = &quot;userID&quot;\n)\n\nfunc middleware(next http.HandlerFunc) http.HandlerFunc {\n    return func(w http.ResponseWriter, r *http.Request) {\n        \/\/ \u6ce8\u5165 traceID\n        traceID := generateTraceID()\n        ctx := context.WithValue(r.Context(), keyTraceID, traceID)\n\n        \/\/ \u6ce8\u5165\u7528\u6237\u4fe1\u606f\n        userID := authenticate(r)\n        ctx = context.WithValue(ctx, keyUserID, userID)\n\n        next(w, r.WithContext(ctx))\n    }\n}\n\nfunc handler(w http.ResponseWriter, r *http.Request) {\n    traceID, _ := r.Context().Value(keyTraceID).(string)\n    userID, _ := r.Context().Value(keyUserID).(string)\n    fmt.Fprintf(w, &quot;trace=%s, user=%s&quot;, traceID, userID)\n}<\/code><\/pre>\n<h2>\u4e09\u3001\u6a2a\u5411\u5bf9\u6bd4\uff1a\u5982\u4f55\u9009\u62e9\u6b63\u786e\u7684 Context<\/h2>\n<p>\u9762\u5bf9\u8fd9\u4e48\u591a\u521b\u5efa\u65b9\u5f0f\uff0c\u5b9e\u9645\u5f00\u53d1\u4e2d\u8be5\u600e\u4e48\u9009\uff1f\u4ee5\u4e0b\u4ece\u591a\u4e2a\u7ef4\u5ea6\u505a\u5bf9\u6bd4\u3002<\/p>\n<h3>WithCancel vs WithTimeout vs WithDeadline<\/h3>\n<table>\n<thead>\n<tr>\n<th>\u7ef4\u5ea6<\/th>\n<th>WithCancel<\/th>\n<th>WithTimeout<\/th>\n<th>WithDeadline<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>\u53d6\u6d88\u65b9\u5f0f<\/td>\n<td>\u624b\u52a8\u8c03\u7528 cancel()<\/td>\n<td>\u8d85\u65f6\u81ea\u52a8 + \u624b\u52a8<\/td>\n<td>\u8d85\u65f6\u81ea\u52a8 + \u624b\u52a8<\/td>\n<\/tr>\n<tr>\n<td>\u65f6\u95f4\u53c2\u6570<\/td>\n<td>\u65e0<\/td>\n<td>\u76f8\u5bf9\u65f6\u957f (Duration)<\/td>\n<td>\u7edd\u5bf9\u65f6\u95f4\u70b9 (Time)<\/td>\n<\/tr>\n<tr>\n<td>\u5e95\u5c42\u5b9e\u73b0<\/td>\n<td>cancelCtx<\/td>\n<td>timerCtx\uff08\u5185\u90e8\u8c03 WithDeadline\uff09<\/td>\n<td>timerCtx<\/td>\n<\/tr>\n<tr>\n<td>\u5178\u578b\u573a\u666f<\/td>\n<td>\u624b\u52a8\u63a7\u5236 goroutine \u751f\u547d\u5468\u671f<\/td>\n<td>\u5355\u6b21\u64cd\u4f5c\u9650\u65f6\uff08DB \u67e5\u8be2\u3001HTTP \u8c03\u7528\uff09<\/td>\n<td>\u591a\u4e2a\u64cd\u4f5c\u5171\u4eab\u540c\u4e00\u622a\u6b62\u65f6\u95f4<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>\u9009\u62e9\u539f\u5219\uff1a<\/p>\n<ul>\n<li>\u4e0d\u9700\u8981\u8d85\u65f6 \u2192 <code>WithCancel<\/code><\/li>\n<li>\u9650\u5236\u5355\u4e2a\u64cd\u4f5c\u8017\u65f6 \u2192 <code>WithTimeout<\/code>\uff08\u66f4\u76f4\u89c2\uff09<\/li>\n<li>\u591a\u4e2a\u64cd\u4f5c\u5171\u4eab\u540c\u4e00\u4e2a\u622a\u6b62\u65f6\u95f4 \u2192 <code>WithDeadline<\/code>\uff08\u907f\u514d\u5404\u81ea\u8ba1\u7b97\u5269\u4f59\u65f6\u95f4\uff09<\/li>\n<\/ul>\n<pre><code class=\"go\">\/\/ \u573a\u666f\uff1a\u4e00\u4e2a\u8bf7\u6c42\u5185\uff0cDB \u548c Redis \u5fc5\u987b\u5728\u540c\u4e00\u65f6\u523b\u524d\u5b8c\u6210\ndeadline := time.Now().Add(5 * time.Second)\n\n\/\/ \u7528 WithDeadline\uff1a\u4e24\u4e2a\u64cd\u4f5c\u5171\u4eab\u622a\u6b62\u65f6\u95f4\uff0c\u8bed\u4e49\u6e05\u6670\ndbCtx, c1 := context.WithDeadline(ctx, deadline)\ndefer c1()\nredisCtx, c2 := context.WithDeadline(ctx, deadline)\ndefer c2()\n\n\/\/ \u7528 WithTimeout\uff1a\u9700\u8981\u5404\u81ea\u8ba1\u7b97\u5269\u4f59\u65f6\u95f4\uff0c\u5bb9\u6613\u51fa\u73b0\u5fae\u5c0f\u504f\u5dee\ndbCtx, c1 := context.WithTimeout(ctx, 5*time.Second)    \/\/ \u4ece\u73b0\u5728\u5f00\u59cb 5 \u79d2\ndefer c1()\n\/\/ ... \u4e2d\u95f4\u53ef\u80fd\u5df2\u7ecf\u8fc7\u4e86\u51e0\u6beb\u79d2\nredisCtx, c2 := context.WithTimeout(ctx, 5*time.Second) \/\/ \u53c8\u4ece\u73b0\u5728\u5f00\u59cb 5 \u79d2\uff0c\u6bd4 DB \u665a\ndefer c2()<\/code><\/pre>\n<h3>\u666e\u901a\u7248 vs Cause \u7248<\/h3>\n<table>\n<thead>\n<tr>\n<th>\u7ef4\u5ea6<\/th>\n<th>WithCancel \/ WithTimeout<\/th>\n<th>WithCancelCause \/ WithTimeoutCause<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>\u53d6\u6d88\u540e Err()<\/td>\n<td><code>context.Canceled<\/code> \u6216 <code>DeadlineExceeded<\/code><\/td>\n<td>\u540c\u5de6\uff08\u4e0d\u53d8\uff09<\/td>\n<\/tr>\n<tr>\n<td>\u53d6\u6d88\u540e Cause()<\/td>\n<td>\u7b49\u540c\u4e8e Err()<\/td>\n<td>\u8fd4\u56de\u4f60\u4f20\u5165\u7684\u81ea\u5b9a\u4e49 error<\/td>\n<\/tr>\n<tr>\n<td>\u9002\u7528\u573a\u666f<\/td>\n<td>\u53ea\u9700\u77e5\u9053&#8221;\u88ab\u53d6\u6d88\u4e86&#8221;<\/td>\n<td>\u9700\u8981\u77e5\u9053&#8221;\u4e3a\u4ec0\u4e48\u88ab\u53d6\u6d88&#8221;<\/td>\n<\/tr>\n<tr>\n<td>\u6027\u80fd\u5f00\u9500<\/td>\n<td>\u7565\u4f4e<\/td>\n<td>\u591a\u5b58\u4e00\u4e2a cause \u5b57\u6bb5\uff0c\u53ef\u5ffd\u7565<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>\u9009\u62e9\u539f\u5219\uff1a<\/p>\n<ul>\n<li>\u7b80\u5355\u573a\u666f\uff08\u5355\u5c42\u8c03\u7528\uff09\u2192 \u666e\u901a\u7248\u8db3\u591f<\/li>\n<li>\u5fae\u670d\u52a1\u94fe\u8def \/ \u9700\u8981\u7cbe\u786e\u6392\u67e5\u8d85\u65f6\u539f\u56e0 \u2192 Cause \u7248<\/li>\n<\/ul>\n<pre><code class=\"go\">\/\/ \u666e\u901a\u7248\uff1a\u53ea\u77e5\u9053\u8d85\u65f6\u4e86\nctx, cancel := context.WithTimeout(parentCtx, 2*time.Second)\ndefer cancel()\n\/\/ ctx.Err() \u2192 &quot;context deadline exceeded&quot;  \u4f46\u4e0d\u77e5\u9053\u662f\u54ea\u4e2a\u73af\u8282\n\n\/\/ Cause \u7248\uff1a\u7cbe\u786e\u5b9a\u4f4d\nctx, cancel := context.WithTimeoutCause(parentCtx, 2*time.Second,\n    fmt.Errorf(&quot;\u8c03\u7528\u7528\u6237\u670d\u52a1\u8d85\u65f6&quot;))\ndefer cancel()\n\/\/ context.Cause(ctx) \u2192 &quot;\u8c03\u7528\u7528\u6237\u670d\u52a1\u8d85\u65f6&quot;  \u4e00\u76ee\u4e86\u7136<\/code><\/pre>\n<h3>WithoutCancel vs \u76f4\u63a5\u4f20\u7236 context<\/h3>\n<blockquote><p><code>WithoutCancel<\/code> \u548c <code>AfterFunc<\/code> \u662f Go 1.21 \u65b0\u589e\u7684 API\uff0c\u8be6\u89c1<a href=\"https:\/\/segmentfault.com\/a\/#\u4e03context-api-\u6f14\u8fdbgo-120--126\" target=\"_blank\" rel=\"noopener noreferrer\">\u7b2c\u4e03\u8282<\/a>\u3002\u8fd9\u91cc\u5148\u4ece\u9009\u578b\u89d2\u5ea6\u505a\u5bf9\u6bd4\u3002<\/p><\/blockquote>\n<table>\n<thead>\n<tr>\n<th>\u7ef4\u5ea6<\/th>\n<th>\u4f20\u7236 context<\/th>\n<th>WithoutCancel<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>\u7236\u53d6\u6d88\u65f6<\/td>\n<td>\u5b50\u4e5f\u53d6\u6d88<\/td>\n<td>\u5b50\u4e0d\u53d7\u5f71\u54cd<\/td>\n<\/tr>\n<tr>\n<td>\u7ee7\u627f Value<\/td>\n<td>\u662f<\/td>\n<td>\u662f<\/td>\n<\/tr>\n<tr>\n<td>\u7ee7\u627f Deadline<\/td>\n<td>\u662f<\/td>\n<td>\u5426<\/td>\n<\/tr>\n<tr>\n<td>\u5178\u578b\u573a\u666f<\/td>\n<td>\u7edd\u5927\u591a\u6570\u60c5\u51b5<\/td>\n<td>\u8bf7\u6c42\u7ed3\u675f\u540e\u7684\u5f02\u6b65\u4efb\u52a1\uff08\u5ba1\u8ba1\u65e5\u5fd7\u3001\u6307\u6807\u4e0a\u62a5\uff09<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p><strong>\u6ce8\u610f<\/strong>\uff1a<code>WithoutCancel<\/code> \u8fd4\u56de\u7684 context \u6ca1\u6709 <code>Done()<\/code> channel\uff08\u8fd4\u56de nil\uff09\uff0c\u4e5f\u6ca1\u6709 <code>Deadline<\/code>\u3002\u5982\u679c\u4f60\u7684\u5f02\u6b65\u4efb\u52a1\u672c\u8eab\u4e5f\u9700\u8981\u8d85\u65f6\u63a7\u5236\uff0c\u9700\u8981\u518d\u5957\u4e00\u5c42 <code>WithTimeout<\/code>\uff1a<\/p>\n<pre><code class=\"go\">func handler(w http.ResponseWriter, r *http.Request) {\n    \/\/ \u8131\u79bb\u8bf7\u6c42\u751f\u547d\u5468\u671f\uff0c\u4f46\u7ed9\u5f02\u6b65\u4efb\u52a1\u8bbe\u7f6e\u72ec\u7acb\u8d85\u65f6\n    asyncCtx := context.WithoutCancel(r.Context())\n    asyncCtx, cancel := context.WithTimeout(asyncCtx, 10*time.Second)\n\n    go func() {\n        defer cancel()\n        writeAuditLog(asyncCtx, &quot;user accessed resource&quot;)\n    }()\n}<\/code><\/pre>\n<h3>\u5feb\u901f\u9009\u578b\u6307\u5357<\/h3>\n<table>\n<thead>\n<tr>\n<th>\u4f60\u7684\u9700\u6c42<\/th>\n<th>\u9009\u62e9<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>\u4ec5\u4f20\u503c\uff0c\u4e0d\u9700\u8981\u53d6\u6d88<\/td>\n<td><code>WithValue<\/code><\/td>\n<\/tr>\n<tr>\n<td>\u624b\u52a8\u53d6\u6d88 goroutine<\/td>\n<td><code>WithCancel<\/code> \/ <code>WithCancelCause<\/code><\/td>\n<\/tr>\n<tr>\n<td>\u9650\u5236\u64cd\u4f5c\u8017\u65f6<\/td>\n<td><code>WithTimeout<\/code> \/ <code>WithTimeoutCause<\/code><\/td>\n<\/tr>\n<tr>\n<td>\u591a\u64cd\u4f5c\u5171\u4eab\u622a\u6b62\u65f6\u95f4<\/td>\n<td><code>WithDeadline<\/code> \/ <code>WithDeadlineCause<\/code><\/td>\n<\/tr>\n<tr>\n<td>\u8131\u79bb\u7236 context \u751f\u547d\u5468\u671f<\/td>\n<td><code>WithoutCancel<\/code><\/td>\n<\/tr>\n<tr>\n<td>\u53d6\u6d88\u540e\u6267\u884c\u6e05\u7406\u56de\u8c03<\/td>\n<td><code>AfterFunc<\/code><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>\u9700\u8981\u6392\u67e5&#8221;\u4e3a\u4ec0\u4e48\u88ab\u53d6\u6d88&#8221;\u65f6\uff0c\u9009 Cause \u7248\u672c\u3002<\/p>\n<h2>\u56db\u3001Context \u7684\u6811\u5f62\u7ed3\u6784<\/h2>\n<p>Context \u7684\u6838\u5fc3\u8bbe\u8ba1\u662f<strong>\u7236\u5b50\u5173\u7cfb\u5f62\u6210\u7684\u6811<\/strong>\u3002\u7406\u89e3\u8fd9\u68f5\u6811\uff0c\u5c31\u7406\u89e3\u4e86 context \u7684\u7cbe\u9ad3\u3002<\/p>\n<pre><code>Background (\u6839)\n\u251c\u2500\u2500 WithCancel (\u8bf7\u6c42\u7ea7)\n\u2502   \u251c\u2500\u2500 WithTimeout (\u6570\u636e\u5e93\u67e5\u8be2, 2s)\n\u2502   \u251c\u2500\u2500 WithTimeout (Redis \u67e5\u8be2, 1s)\n\u2502   \u2514\u2500\u2500 WithCancel (\u4e0b\u6e38 RPC \u8c03\u7528)\n\u2502       \u251c\u2500\u2500 WithTimeout (\u670d\u52a1A, 3s)\n\u2502       \u2514\u2500\u2500 WithTimeout (\u670d\u52a1B, 3s)<\/code><\/pre>\n<p>\u5173\u952e\u89c4\u5219\uff1a<\/p>\n<ul>\n<li><strong>\u53d6\u6d88\u5411\u4e0b\u4f20\u64ad<\/strong>\uff1a\u7236 context \u53d6\u6d88\u65f6\uff0c\u6240\u6709\u5b50 context \u81ea\u52a8\u53d6\u6d88<\/li>\n<li><strong>\u53d6\u6d88\u4e0d\u5411\u4e0a\u4f20\u64ad<\/strong>\uff1a\u5b50 context \u53d6\u6d88\u4e0d\u5f71\u54cd\u7236 context<\/li>\n<li><strong>\u8d85\u65f6\u53d6\u6700\u77ed<\/strong>\uff1a\u5b50 context \u7684\u8d85\u65f6\u4e0d\u80fd\u8d85\u8fc7\u7236 context \u7684\u5269\u4f59\u65f6\u95f4<\/li>\n<\/ul>\n<pre><code class=\"go\">func main() {\n    \/\/ \u7236 context: 5 \u79d2\u8d85\u65f6\n    parent, cancelParent := context.WithTimeout(context.Background(), 5*time.Second)\n    defer cancelParent()\n\n    \/\/ \u5b50 context: 2 \u79d2\u8d85\u65f6 \u2014 \u5b9e\u9645\u751f\u6548 2 \u79d2\n    child1, cancel1 := context.WithTimeout(parent, 2*time.Second)\n    defer cancel1()\n\n    \/\/ \u5b50 context: 10 \u79d2\u8d85\u65f6 \u2014 \u5b9e\u9645\u751f\u6548 5 \u79d2\uff08\u53d7\u7236 context \u9650\u5236\uff09\n    child2, cancel2 := context.WithTimeout(parent, 10*time.Second)\n    defer cancel2()\n\n    select {\n    case &lt;-child1.Done():\n        fmt.Println(&quot;child1 \u8d85\u65f6&quot;) \/\/ 2 \u79d2\u540e\u89e6\u53d1\n    }\n\n    select {\n    case &lt;-child2.Done():\n        fmt.Println(&quot;child2 \u8d85\u65f6&quot;) \/\/ 5 \u79d2\u540e\u89e6\u53d1\uff08\u8ddf\u968f\u7236 context\uff09\n    }\n}<\/code><\/pre>\n<h2>\u4e94\u3001\u5b9e\u6218\uff1aHTTP \u670d\u52a1\u4e2d\u7684 Context<\/h2>\n<p>\u4e00\u4e2a\u5b8c\u6574\u7684\u4f8b\u5b50\uff0c\u5c55\u793a context \u5728\u771f\u5b9e HTTP \u670d\u52a1\u4e2d\u7684\u4f7f\u7528\u65b9\u5f0f\uff1a<\/p>\n<pre><code class=\"go\">package main\n\nimport (\n    &quot;context&quot;\n    &quot;encoding\/json&quot;\n    &quot;fmt&quot;\n    &quot;log&quot;\n    &quot;net\/http&quot;\n    &quot;time&quot;\n)\n\ntype contextKey string\n\nconst keyRequestID contextKey = &quot;requestID&quot;\n\n\/\/ \u6a21\u62df\u6570\u636e\u5e93\u67e5\u8be2\nfunc fetchUser(ctx context.Context, id string) (map[string]string, error) {\n    dbCtx, cancel := context.WithTimeout(ctx, 2*time.Second)\n    defer cancel()\n\n    select {\n    case &lt;-time.After(1 * time.Second): \/\/ \u6b63\u5e38\u60c5\u51b5 1 \u79d2\u8fd4\u56de\n        return map[string]string{&quot;id&quot;: id, &quot;name&quot;: &quot;\u5f20\u4e09&quot;}, nil\n    case &lt;-dbCtx.Done():\n        return nil, fmt.Errorf(&quot;\u6570\u636e\u5e93\u67e5\u8be2\u8d85\u65f6: %w&quot;, dbCtx.Err())\n    }\n}\n\n\/\/ \u6a21\u62df\u8c03\u7528\u4e0b\u6e38\u670d\u52a1\nfunc fetchOrders(ctx context.Context, userID string) ([]string, error) {\n    select {\n    case &lt;-time.After(500 * time.Millisecond):\n        return []string{&quot;order-001&quot;, &quot;order-002&quot;}, nil\n    case &lt;-ctx.Done():\n        return nil, fmt.Errorf(&quot;\u83b7\u53d6\u8ba2\u5355\u5931\u8d25: %w&quot;, ctx.Err())\n    }\n}\n\nfunc userHandler(w http.ResponseWriter, r *http.Request) {\n    ctx := r.Context()\n    reqID := ctx.Value(keyRequestID)\n\n    log.Printf(&quot;[%s] \u5f00\u59cb\u5904\u7406\u8bf7\u6c42&quot;, reqID)\n\n    \/\/ \u5e76\u53d1\u67e5\u8be2\u7528\u6237\u4fe1\u606f\u548c\u8ba2\u5355\n    type userResult struct {\n        data map[string]string\n        err  error\n    }\n    type orderResult struct {\n        data []string\n        err  error\n    }\n\n    userCh := make(chan userResult, 1)\n    orderCh := make(chan orderResult, 1)\n\n    go func() {\n        data, err := fetchUser(ctx, &quot;123&quot;)\n        userCh &lt;- userResult{data, err}\n    }()\n\n    go func() {\n        data, err := fetchOrders(ctx, &quot;123&quot;)\n        orderCh &lt;- orderResult{data, err}\n    }()\n\n    \/\/ \u7b49\u5f85\u7ed3\u679c\uff0c\u540c\u65f6\u76d1\u542c context \u53d6\u6d88\n    var user map[string]string\n    var orders []string\n\n    for i := 0; i &lt; 2; i++ {\n        select {\n        case ur := &lt;-userCh:\n            if ur.err != nil {\n                http.Error(w, ur.err.Error(), http.StatusInternalServerError)\n                return\n            }\n            user = ur.data\n        case or := &lt;-orderCh:\n            if or.err != nil {\n                http.Error(w, or.err.Error(), http.StatusInternalServerError)\n                return\n            }\n            orders = or.data\n        case &lt;-ctx.Done():\n            log.Printf(&quot;[%s] \u8bf7\u6c42\u88ab\u53d6\u6d88: %v&quot;, reqID, ctx.Err())\n            return\n        }\n    }\n\n    resp := map[string]any{&quot;user&quot;: user, &quot;orders&quot;: orders}\n    json.NewEncoder(w).Encode(resp)\n    log.Printf(&quot;[%s] \u8bf7\u6c42\u5904\u7406\u5b8c\u6210&quot;, reqID)\n}\n\n\/\/ \u4e2d\u95f4\u4ef6\uff1a\u6ce8\u5165 requestID + \u8bbe\u7f6e\u603b\u8d85\u65f6\nfunc withRequestContext(next http.HandlerFunc) http.HandlerFunc {\n    return func(w http.ResponseWriter, r *http.Request) {\n        ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)\n        defer cancel()\n\n        reqID := fmt.Sprintf(&quot;req-%d&quot;, time.Now().UnixNano()) \/\/ \u793a\u4f8b\u7b80\u5316\uff0c\u751f\u4ea7\u73af\u5883\u5efa\u8bae\u7528 UUID\n        ctx = context.WithValue(ctx, keyRequestID, reqID)\n\n        next(w, r.WithContext(ctx))\n    }\n}\n\nfunc main() {\n    http.HandleFunc(&quot;\/user&quot;, withRequestContext(userHandler))\n    log.Println(&quot;\u670d\u52a1\u542f\u52a8\u5728 :8080&quot;)\n    log.Fatal(http.ListenAndServe(&quot;:8080&quot;, nil))\n}<\/code><\/pre>\n<h2>\u516d\u3001\u4f7f\u7528 Context \u7684\u6700\u4f73\u5b9e\u8df5<\/h2>\n<h3>1. \u59cb\u7ec8 defer cancel()<\/h3>\n<pre><code class=\"go\">ctx, cancel := context.WithTimeout(parentCtx, 5*time.Second)\ndefer cancel() \/\/ \u5373\u4f7f\u64cd\u4f5c\u63d0\u524d\u5b8c\u6210\uff0c\u4e5f\u8981\u91ca\u653e\u8d44\u6e90<\/code><\/pre>\n<p>\u4e0d\u8c03\u7528 <code>cancel()<\/code> \u4f1a\u5bfc\u81f4 context \u5185\u90e8\u7684 timer \u6cc4\u6f0f\uff0c\u76f4\u5230\u7236 context \u88ab\u53d6\u6d88\u3002<\/p>\n<h3>2. context \u4f5c\u4e3a\u51fd\u6570\u7b2c\u4e00\u4e2a\u53c2\u6570<\/h3>\n<p>\u8fd9\u662f Go \u793e\u533a\u7684\u5f3a\u7ea6\u5b9a\uff1a<\/p>\n<pre><code class=\"go\">\/\/ \u6b63\u786e\nfunc GetUser(ctx context.Context, id string) (*User, error)\n\n\/\/ \u9519\u8bef \u2014 \u4e0d\u8981\u628a context \u653e\u5728\u5176\u4ed6\u4f4d\u7f6e\nfunc GetUser(id string, ctx context.Context) (*User, error)\n\n\/\/ \u9519\u8bef \u2014 \u4e0d\u8981\u628a context \u653e\u5728\u7ed3\u6784\u4f53\u91cc\ntype Service struct {\n    ctx context.Context \/\/ \u4e0d\u63a8\u8350\n}<\/code><\/pre>\n<h3>3. \u4e0d\u8981\u7528 WithValue \u4f20\u9012\u4e1a\u52a1\u53c2\u6570<\/h3>\n<p><code>WithValue<\/code> \u5e94\u8be5\u53ea\u7528\u4e8e\u4f20\u9012 request-scoped \u7684\u5143\u6570\u636e\uff08traceID\u3001\u8ba4\u8bc1\u4fe1\u606f\u7b49\uff09\uff0c\u4e0d\u8981\u7528\u5b83\u66ff\u4ee3\u51fd\u6570\u53c2\u6570\uff1a<\/p>\n<pre><code class=\"go\">\/\/ \u9519\u8bef \u2014 \u628a\u4e1a\u52a1\u53c2\u6570\u585e\u8fdb context\nctx = context.WithValue(ctx, &quot;userID&quot;, userID)\nctx = context.WithValue(ctx, &quot;page&quot;, 1)\nctx = context.WithValue(ctx, &quot;pageSize&quot;, 20)\nresult := queryUsers(ctx)\n\n\/\/ \u6b63\u786e \u2014 \u4e1a\u52a1\u53c2\u6570\u8d70\u51fd\u6570\u7b7e\u540d\nresult := queryUsers(ctx, userID, page, pageSize)<\/code><\/pre>\n<p>\u539f\u56e0\uff1a<code>Value()<\/code> \u8fd4\u56de <code>any<\/code>\uff0c\u6ca1\u6709\u7c7b\u578b\u5b89\u5168\uff0c\u4e5f\u6ca1\u6709\u7f16\u8bd1\u671f\u68c0\u67e5\u3002<\/p>\n<h3>4. \u68c0\u67e5 context \u662f\u5426\u5df2\u53d6\u6d88<\/h3>\n<p>\u5728\u957f\u65f6\u95f4\u8fd0\u884c\u7684\u5faa\u73af\u4e2d\uff0c\u5b9a\u671f\u68c0\u67e5 context \u72b6\u6001\uff1a<\/p>\n<pre><code class=\"go\">func processItems(ctx context.Context, items []Item) error {\n    for i, item := range items {\n        \/\/ \u6bcf\u6b21\u8fed\u4ee3\u68c0\u67e5\u662f\u5426\u88ab\u53d6\u6d88\n        if ctx.Err() != nil {\n            return fmt.Errorf(&quot;\u5904\u7406\u5728\u7b2c %d \u9879\u4e2d\u65ad: %w&quot;, i, ctx.Err())\n        }\n        process(item)\n    }\n    return nil\n}<\/code><\/pre>\n<h3>5. \u5408\u7406\u8bbe\u7f6e\u8d85\u65f6\u5c42\u7ea7<\/h3>\n<pre><code class=\"go\">\/\/ \u8bf7\u6c42\u603b\u8d85\u65f6 10 \u79d2\nreqCtx, cancel := context.WithTimeout(ctx, 10*time.Second)\ndefer cancel()\n\n\/\/ \u6570\u636e\u5e93\u67e5\u8be2 3 \u79d2\uff08\u5728\u8bf7\u6c42\u8d85\u65f6\u5185\uff09\ndbCtx, dbCancel := context.WithTimeout(reqCtx, 3*time.Second)\ndefer dbCancel()\n\n\/\/ \u7f13\u5b58\u67e5\u8be2 1 \u79d2\uff08\u5728\u8bf7\u6c42\u8d85\u65f6\u5185\uff09\ncacheCtx, cacheCancel := context.WithTimeout(reqCtx, 1*time.Second)\ndefer cacheCancel()<\/code><\/pre>\n<h2>\u4e03\u3001Context API \u6f14\u8fdb\uff08Go 1.20 \u2192 1.26\uff09<\/h2>\n<p>context \u5305\u5728 Go 1.20 \u4e4b\u540e\u7ecf\u5386\u4e86\u4e00\u8f6e\u91cd\u8981\u7684 API \u6269\u5c55\u3002\u4ee5\u4e0b\u6309\u7248\u672c\u68b3\u7406\u6240\u6709\u65b0\u589e\u5185\u5bb9\u3002<\/p>\n<h3>Go 1.20\uff1aCause \u7cfb\u5217 \u2014 \u8ba9\u53d6\u6d88\u539f\u56e0\u53ef\u8ffd\u6eaf<\/h3>\n<p>\u5728 Go 1.20 \u4e4b\u524d\uff0ccontext \u88ab\u53d6\u6d88\u540e\u53ea\u80fd\u901a\u8fc7 <code>Err()<\/code> \u5f97\u5230 <code>context.Canceled<\/code> \u6216 <code>context.DeadlineExceeded<\/code>\uff0c\u65e0\u6cd5\u77e5\u9053&#8221;\u4e3a\u4ec0\u4e48\u88ab\u53d6\u6d88&#8221;\u3002Cause \u7cfb\u5217 API \u89e3\u51b3\u4e86\u8fd9\u4e2a\u95ee\u9898\u3002<\/p>\n<p><strong>WithCancelCause<\/strong> \u2014 \u53d6\u6d88\u65f6\u9644\u5e26\u81ea\u5b9a\u4e49\u9519\u8bef\uff1a<\/p>\n<pre><code class=\"go\">ctx, cancel := context.WithCancelCause(parentCtx)\n\n\/\/ \u53d6\u6d88\u65f6\u4f20\u5165\u5177\u4f53\u539f\u56e0\ncancel(fmt.Errorf(&quot;\u4e0a\u6e38\u670d\u52a1 %s \u8fd4\u56de 503&quot;, serviceName))\n\n\/\/ \u83b7\u53d6\u53d6\u6d88\u539f\u56e0\ncause := context.Cause(ctx)\nfmt.Println(cause) \/\/ &quot;\u4e0a\u6e38\u670d\u52a1 xxx \u8fd4\u56de 503&quot;\n\n\/\/ Err() \u4ecd\u7136\u8fd4\u56de context.Canceled\uff0c\u4f46 Cause() \u8fd4\u56de\u4f60\u4f20\u5165\u7684\u9519\u8bef\nfmt.Println(ctx.Err()) \/\/ context canceled<\/code><\/pre>\n<h3>Go 1.21\uff1a\u56db\u4e2a\u91cd\u8981\u65b0\u589e<\/h3>\n<p><strong>WithDeadlineCause \/ WithTimeoutCause<\/strong> \u2014 \u8d85\u65f6\u65f6\u9644\u5e26\u81ea\u5b9a\u4e49\u539f\u56e0\uff1a<\/p>\n<pre><code class=\"go\">\/\/ WithTimeoutCause\uff1a\u76f8\u5bf9\u65f6\u95f4\u7248\u672c\nctx, cancel := context.WithTimeoutCause(\n    parentCtx,\n    2*time.Second,\n    fmt.Errorf(&quot;\u8c03\u7528\u652f\u4ed8\u670d\u52a1\u8d85\u65f6&quot;),\n)\ndefer cancel()\n\nselect {\ncase &lt;-time.After(5 * time.Second):\n    fmt.Println(&quot;\u5b8c\u6210&quot;)\ncase &lt;-ctx.Done():\n    fmt.Println(context.Cause(ctx)) \/\/ &quot;\u8c03\u7528\u652f\u4ed8\u670d\u52a1\u8d85\u65f6&quot;\n}\n\n\/\/ WithDeadlineCause\uff1a\u7edd\u5bf9\u65f6\u95f4\u7248\u672c\uff0c\u7528\u6cd5\u7c7b\u4f3c\n\/\/ ctx, cancel := context.WithDeadlineCause(parentCtx, time.Now().Add(3*time.Second), cause)<\/code><\/pre>\n<p>\u5f53\u4e00\u4e2a\u8bf7\u6c42\u94fe\u8def\u6d89\u53ca\u591a\u4e2a\u4e0b\u6e38\u8c03\u7528\u65f6\uff0c\u6bcf\u4e2a\u8c03\u7528\u90fd\u53ef\u4ee5\u9644\u5e26\u72ec\u7acb\u7684\u8d85\u65f6\u539f\u56e0\uff0c\u6392\u67e5\u95ee\u9898\u65f6\u4e00\u76ee\u4e86\u7136\u3002<\/p>\n<p><strong>WithoutCancel<\/strong> \u2014 \u521b\u5efa\u4e0d\u968f\u7236 context \u53d6\u6d88\u7684\u5b50 context\uff0c\u4f46\u4ecd\u7ee7\u627f <code>Value<\/code>\uff1a<\/p>\n<pre><code class=\"go\">\/\/ \u573a\u666f\uff1a\u8bf7\u6c42\u7ed3\u675f\u540e\u4ecd\u9700\u6267\u884c\u7684\u5f02\u6b65\u4efb\u52a1\uff08\u5982\u5199\u5ba1\u8ba1\u65e5\u5fd7\uff09\nfunc handler(w http.ResponseWriter, r *http.Request) {\n    \/\/ \u8bf7\u6c42\u7ed3\u675f\u540e r.Context() \u4f1a\u88ab\u53d6\u6d88\n    \/\/ \u4f46\u5ba1\u8ba1\u65e5\u5fd7\u9700\u8981\u7ee7\u7eed\u6267\u884c\n    auditCtx := context.WithoutCancel(r.Context())\n    go writeAuditLog(auditCtx, &quot;user accessed resource&quot;)\n}<\/code><\/pre>\n<p><strong>AfterFunc<\/strong> \u2014 \u5728 context \u53d6\u6d88\u540e\u6267\u884c\u56de\u8c03\uff1a<\/p>\n<pre><code class=\"go\">ctx, cancel := context.WithCancel(parentCtx)\ndefer cancel()\n\nstop := context.AfterFunc(ctx, func() {\n    log.Println(&quot;context \u88ab\u53d6\u6d88\uff0c\u6267\u884c\u6e05\u7406\u5de5\u4f5c&quot;)\n    cleanup()\n})\ndefer stop() \/\/ \u5982\u679c\u4e0d\u518d\u9700\u8981\u56de\u8c03\uff0c\u53ef\u4ee5\u63d0\u524d\u53d6\u6d88\u6ce8\u518c<\/code><\/pre>\n<h3>Go 1.24\uff1atesting \u5305\u96c6\u6210 Context<\/h3>\n<p>Go 1.24 \u4e3a <code>testing.T<\/code> \u548c <code>testing.B<\/code> \u65b0\u589e\u4e86 <code>Context()<\/code> \u65b9\u6cd5\uff0c\u8fd4\u56de\u4e00\u4e2a\u5728\u6d4b\u8bd5\u7ed3\u675f\u540e\uff08cleanup \u4e4b\u524d\uff09\u81ea\u52a8\u53d6\u6d88\u7684 context\uff1a<\/p>\n<pre><code class=\"go\">func TestUserService(t *testing.T) {\n    \/\/ \u4e0d\u518d\u9700\u8981\u624b\u52a8\u521b\u5efa context\n    \/\/ t.Context() \u4f1a\u5728\u6d4b\u8bd5\u7ed3\u675f\u65f6\u81ea\u52a8\u53d6\u6d88\n    ctx := t.Context()\n\n    user, err := service.GetUser(ctx, &quot;123&quot;)\n    if err != nil {\n        t.Fatal(err)\n    }\n    \/\/ ...\n}<\/code><\/pre>\n<p>\u8fd9\u6d88\u9664\u4e86\u6d4b\u8bd5\u4ee3\u7801\u4e2d\u5927\u91cf\u7684 <code>context.Background()<\/code> \u6837\u677f\uff0c\u4e5f\u8ba9\u6d4b\u8bd5\u8d85\u65f6\u80fd\u81ea\u52a8\u4f20\u64ad\u5230\u88ab\u6d4b\u51fd\u6570\u3002<\/p>\n<h3>Go 1.26\uff1a\u751f\u6001\u6301\u7eed\u5b8c\u5584<\/h3>\n<p>Go 1.26 \u672c\u8eab\u6ca1\u6709\u5bf9 context \u5305\u65b0\u589e API\uff0c\u4f46\u76f8\u5173\u751f\u6001\u6709\u91cd\u8981\u53d8\u5316\uff1a<\/p>\n<ul>\n<li><strong>Green Tea GC \u9ed8\u8ba4\u542f\u7528<\/strong>\uff1aGC \u5f00\u9500\u964d\u4f4e 10\u201340%\uff0c\u9ad8\u5e76\u53d1\u573a\u666f\u4e0b\u5927\u91cf context \u7684\u521b\u5efa\u548c\u56de\u6536\u66f4\u9ad8\u6548<\/li>\n<li><strong>cgo \u8c03\u7528\u5f00\u9500\u964d\u4f4e\u7ea6 30%<\/strong>\uff1a\u5982\u679c\u4f60\u7684 context \u8de8\u8d8a cgo \u8fb9\u754c\uff08\u5982\u8c03\u7528 C \u5e93\uff09\uff0c\u6027\u80fd\u663e\u8457\u63d0\u5347<\/li>\n<li><strong><code>errors.AsType<\/code> \u6cdb\u578b\u51fd\u6570<\/strong>\uff1a\u914d\u5408 <code>context.Cause()<\/code> \u4f7f\u7528\uff0c\u7c7b\u578b\u5b89\u5168\u5730\u63d0\u53d6\u53d6\u6d88\u539f\u56e0\u4e2d\u7684\u7279\u5b9a\u9519\u8bef\u7c7b\u578b<\/li>\n<\/ul>\n<pre><code class=\"go\">\/\/ Go 1.26: \u7528 errors.AsType \u66ff\u4ee3 errors.As\uff0c\u66f4\u7b80\u6d01\nctx, cancel := context.WithCancelCause(parentCtx)\ncancel(&amp;TimeoutError{Service: &quot;payment&quot;, Duration: 3 * time.Second})\n\n\/\/ \u7c7b\u578b\u5b89\u5168\u5730\u63d0\u53d6 cause\nif te, ok := errors.AsType[*TimeoutError](context.Cause(ctx)); ok {\n    log.Printf(&quot;\u670d\u52a1 %s \u8d85\u65f6 %v&quot;, te.Service, te.Duration)\n}<\/code><\/pre>\n<h3>\u5b8c\u6574 API \u901f\u67e5\u8868\uff08\u622a\u81f3 Go 1.26\uff09<\/h3>\n<table>\n<thead>\n<tr>\n<th>\u51fd\u6570<\/th>\n<th>\u5f15\u5165\u7248\u672c<\/th>\n<th>\u4f5c\u7528<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td><code>Background()<\/code><\/td>\n<td>1.7<\/td>\n<td>\u8fd4\u56de\u7a7a\u7684\u6839 context<\/td>\n<\/tr>\n<tr>\n<td><code>TODO()<\/code><\/td>\n<td>1.7<\/td>\n<td>\u5360\u4f4d\u7528\u7684\u7a7a context<\/td>\n<\/tr>\n<tr>\n<td><code>WithValue()<\/code><\/td>\n<td>1.7<\/td>\n<td>\u9644\u52a0\u952e\u503c\u5bf9<\/td>\n<\/tr>\n<tr>\n<td><code>WithCancel()<\/code><\/td>\n<td>1.7<\/td>\n<td>\u624b\u52a8\u53d6\u6d88<\/td>\n<\/tr>\n<tr>\n<td><code>WithDeadline()<\/code><\/td>\n<td>1.7<\/td>\n<td>\u6307\u5b9a\u622a\u6b62\u65f6\u95f4<\/td>\n<\/tr>\n<tr>\n<td><code>WithTimeout()<\/code><\/td>\n<td>1.7<\/td>\n<td>\u6307\u5b9a\u8d85\u65f6\u65f6\u957f<\/td>\n<\/tr>\n<tr>\n<td><code>WithCancelCause()<\/code><\/td>\n<td>1.20<\/td>\n<td>\u53d6\u6d88\u65f6\u9644\u5e26\u539f\u56e0<\/td>\n<\/tr>\n<tr>\n<td><code>Cause()<\/code><\/td>\n<td>1.20<\/td>\n<td>\u83b7\u53d6\u53d6\u6d88\u539f\u56e0<\/td>\n<\/tr>\n<tr>\n<td><code>WithDeadlineCause()<\/code><\/td>\n<td>1.21<\/td>\n<td>\u622a\u6b62\u65f6\u95f4 + \u81ea\u5b9a\u4e49\u539f\u56e0<\/td>\n<\/tr>\n<tr>\n<td><code>WithTimeoutCause()<\/code><\/td>\n<td>1.21<\/td>\n<td>\u8d85\u65f6 + \u81ea\u5b9a\u4e49\u539f\u56e0<\/td>\n<\/tr>\n<tr>\n<td><code>WithoutCancel()<\/code><\/td>\n<td>1.21<\/td>\n<td>\u4e0d\u968f\u7236\u53d6\u6d88\u7684\u5b50 context<\/td>\n<\/tr>\n<tr>\n<td><code>AfterFunc()<\/code><\/td>\n<td>1.21<\/td>\n<td>\u53d6\u6d88\u540e\u6267\u884c\u56de\u8c03<\/td>\n<\/tr>\n<tr>\n<td><code>t.Context()<\/code> \/ <code>b.Context()<\/code><\/td>\n<td>1.24<\/td>\n<td>\u6d4b\u8bd5\u4e2d\u81ea\u52a8\u7ba1\u7406 context<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h2>\u516b\u3001\u5e38\u89c1\u9677\u9631<\/h2>\n<p>\u4e86\u89e3\u4e86 API \u7684\u6f14\u8fdb\uff0c\u518d\u6765\u770b\u770b\u5b9e\u9645\u4f7f\u7528\u4e2d\u6700\u5bb9\u6613\u8e29\u7684\u5751\u3002<\/p>\n<h3>\u9677\u9631 1\uff1a\u5fd8\u8bb0\u8c03\u7528 cancel<\/h3>\n<pre><code class=\"go\">\/\/ \u5185\u5b58\u6cc4\u6f0f\uff01timer \u4e0d\u4f1a\u88ab\u91ca\u653e\nctx, _ := context.WithTimeout(parentCtx, 5*time.Second)<\/code><\/pre>\n<p><code>go vet<\/code> \u4f1a\u5bf9\u6b64\u53d1\u51fa\u8b66\u544a\u3002\u59cb\u7ec8\u63a5\u6536\u5e76 defer \u8c03\u7528 cancel\u3002<\/p>\n<h3>\u9677\u9631 2\uff1a\u7528 string \u7c7b\u578b\u4f5c\u4e3a Value \u7684 key<\/h3>\n<pre><code class=\"go\">\/\/ \u5371\u9669\uff1a\u4e0d\u540c\u5305\u53ef\u80fd\u7528\u76f8\u540c\u7684 string key\uff0c\u5bfc\u81f4\u51b2\u7a81\nctx = context.WithValue(ctx, &quot;userID&quot;, &quot;123&quot;)\n\n\/\/ \u5b89\u5168\uff1a\u81ea\u5b9a\u4e49\u672a\u5bfc\u51fa\u7c7b\u578b\uff0c\u5305\u7ea7\u522b\u9694\u79bb\ntype ctxKey struct{}\nctx = context.WithValue(ctx, ctxKey{}, &quot;123&quot;)<\/code><\/pre>\n<h3>\u9677\u9631 3\uff1a\u5728 context \u53d6\u6d88\u540e\u7ee7\u7eed\u4f7f\u7528<\/h3>\n<pre><code class=\"go\">ctx, cancel := context.WithTimeout(parentCtx, 1*time.Second)\ndefer cancel()\n\nconn, err := db.Conn(ctx)\nif err != nil {\n    return err\n}\n\/\/ \u6b64\u65f6 ctx \u53ef\u80fd\u5df2\u7ecf\u8d85\u65f6\n\/\/ \u7528\u5df2\u53d6\u6d88\u7684 ctx \u6267\u884c\u67e5\u8be2\u4f1a\u7acb\u5373\u5931\u8d25\nrows, err := conn.QueryContext(ctx, &quot;SELECT ...&quot;) \/\/ \u53ef\u80fd\u7acb\u5373\u8fd4\u56de\u9519\u8bef<\/code><\/pre>\n<p>\u89e3\u51b3\u65b9\u6848\uff1a\u5982\u679c\u540e\u7eed\u64cd\u4f5c\u9700\u8981\u72ec\u7acb\u7684\u8d85\u65f6\u63a7\u5236\uff0c\u4e3a\u5b83\u521b\u5efa\u65b0\u7684 context\uff1a<\/p>\n<pre><code class=\"go\">conn, err := db.Conn(ctx)\nif err != nil {\n    return err\n}\nqueryCtx, queryCancel := context.WithTimeout(context.Background(), 3*time.Second)\ndefer queryCancel()\nrows, err := conn.QueryContext(queryCtx, &quot;SELECT ...&quot;)<\/code><\/pre>\n<h2>\u4e5d\u3001\u6e90\u7801\u89e3\u6790\uff1acontext \u7684\u5185\u90e8\u5b9e\u73b0<\/h2>\n<blockquote><p>\u4ee5\u4e0b\u6e90\u7801\u57fa\u4e8e Go 1.26\uff08<code>$GOROOT\/src\/context\/context.go<\/code>\uff09\uff0c\u6838\u5fc3\u903b\u8f91\u81ea Go 1.7 \u4ee5\u6765\u4fdd\u6301\u7a33\u5b9a\u3002\u7406\u89e3\u6e90\u7801\u80fd\u5e2e\u4f60\u5728\u590d\u6742\u573a\u666f\u4e0b\u505a\u51fa\u66f4\u597d\u7684\u5224\u65ad\u3002<\/p><\/blockquote>\n<h3>9.1 \u5185\u90e8\u7c7b\u578b\u603b\u89c8<\/h3>\n<p>\u6574\u4e2a context \u5305\u53ea\u6709\u4e94\u79cd\u6838\u5fc3 struct\uff1a<\/p>\n<pre><code>Context (\u63a5\u53e3)\n\u251c\u2500\u2500 emptyCtx        \u2192 Background() \/ TODO() \u8fd4\u56de\uff08\u503c\u7c7b\u578b\uff0c\u96f6\u5206\u914d\uff0cDone() \u8fd4\u56de nil\uff09\n\u251c\u2500\u2500 cancelCtx       \u2192 WithCancel() \u8fd4\u56de\uff08\u53d6\u6d88\u673a\u5236\u7684\u6838\u5fc3\uff09\n\u2502   \u251c\u2500\u2500 timerCtx    \u2192 WithDeadline() \/ WithTimeout() \u8fd4\u56de\n\u2502   \u2514\u2500\u2500 afterFuncCtx \u2192 AfterFunc() \u5185\u90e8\u4f7f\u7528\n\u251c\u2500\u2500 valueCtx        \u2192 WithValue() \u8fd4\u56de\uff08\u94fe\u8868\u5f0f\u952e\u503c\u5b58\u50a8\uff09\n\u2514\u2500\u2500 withoutCancelCtx \u2192 WithoutCancel() \u8fd4\u56de\uff08\u5207\u65ad\u53d6\u6d88\u94fe\uff0c\u4fdd\u7559 Value\uff09<\/code><\/pre>\n<p><code>emptyCtx<\/code> \u662f\u4e00\u5207\u7684\u8d77\u70b9\u2014\u2014<code>Background()<\/code> \u548c <code>TODO()<\/code> \u8fd4\u56de\u7684\u5c31\u662f\u5b83\u7684\u5305\u88c5\u7c7b\u578b <code>backgroundCtx{}<\/code> \u548c <code>todoCtx{}<\/code>\uff0c\u56db\u4e2a\u65b9\u6cd5\u5168\u90e8\u8fd4\u56de\u96f6\u503c\uff0c\u552f\u4e00\u533a\u522b\u662f <code>String()<\/code> \u8fd4\u56de\u4e0d\u540c\u7684\u540d\u5b57\u65b9\u4fbf\u8c03\u8bd5\u3002<\/p>\n<h3>9.2 cancelCtx \u2014 \u53d6\u6d88\u673a\u5236\u7684\u6838\u5fc3<\/h3>\n<p>\u8fd9\u662f\u6574\u4e2a context \u5305\u6700\u91cd\u8981\u7684\u7ed3\u6784\u4f53\uff1a<\/p>\n<pre><code class=\"go\">\/\/ \u6e90\u7801\ntype cancelCtx struct {\n    Context                          \/\/ \u5d4c\u5165\u7236 context\uff08\u5f62\u6210\u94fe\u8868\/\u6811\uff09\n\n    mu       sync.Mutex             \/\/ \u4fdd\u62a4\u4ee5\u4e0b\u5b57\u6bb5\n    done     atomic.Value           \/\/ chan struct{}\uff0c\u61d2\u521b\u5efa\uff0c\u9996\u6b21 cancel \u65f6\u5173\u95ed\n    children map[canceler]struct{}  \/\/ \u5b50 context \u96c6\u5408\uff0c\u9996\u6b21 cancel \u65f6\u7f6e nil\n    err      atomic.Value           \/\/ \u9996\u6b21 cancel \u65f6\u8bbe\u7f6e\n    cause    error                  \/\/ \u53d6\u6d88\u539f\u56e0\uff08Cause \u7cfb\u5217 API \u4f7f\u7528\uff09\n}<\/code><\/pre>\n<p>\u5173\u952e\u8bbe\u8ba1\u70b9\uff1a<\/p>\n<p><strong>1) Done() channel \u61d2\u521b\u5efa<\/strong><\/p>\n<pre><code class=\"go\">\/\/ \u6e90\u7801\nfunc (c *cancelCtx) Done() &lt;-chan struct{} {\n    d := c.done.Load()\n    if d != nil {\n        return d.(chan struct{})\n    }\n    c.mu.Lock()\n    defer c.mu.Unlock()\n    d = c.done.Load()\n    if d == nil {\n        d = make(chan struct{})\n        c.done.Store(d)\n    }\n    return d.(chan struct{})\n}<\/code><\/pre>\n<p>\u4f7f\u7528\u4e86 double-check locking \u6a21\u5f0f\uff1a\u5148\u7528 atomic \u65e0\u9501\u5feb\u901f\u68c0\u67e5\uff0cmiss \u540e\u624d\u52a0\u9501\u521b\u5efa\u3002\u5982\u679c\u4e00\u4e2a context \u4ece\u672a\u88ab <code>select<\/code> \u76d1\u542c\u8fc7 <code>Done()<\/code>\uff0cchannel \u5c31\u4e0d\u4f1a\u88ab\u521b\u5efa\uff0c\u8282\u7701\u5185\u5b58\u3002<\/p>\n<p><strong>2) Err() \u7528 atomic \u800c\u975e mutex<\/strong><\/p>\n<pre><code class=\"go\">\/\/ \u6e90\u7801\nfunc (c *cancelCtx) Err() error {\n    if err := c.err.Load(); err != nil {\n        &lt;-c.Done()  \/\/ \u786e\u4fdd done channel \u5df2\u5173\u95ed\n        return err.(error)\n    }\n    return nil\n}<\/code><\/pre>\n<p>\u6e90\u7801\u6ce8\u91ca\u8bf4\u5f97\u5f88\u76f4\u767d\uff1a<code>atomic load \u6bd4 mutex \u5feb\u7ea6 5 \u500d<\/code>\u3002\u5728\u9ad8\u9891\u8c03\u7528 <code>ctx.Err()<\/code> \u7684\u70ed\u5faa\u73af\u4e2d\uff0c\u8fd9\u4e2a\u4f18\u5316\u5f88\u6709\u610f\u4e49\u3002\u6ce8\u610f\u5b83\u5728\u8fd4\u56de\u975e nil error \u524d\u4f1a\u5148 <code>&lt;-c.Done()<\/code>\uff0c\u786e\u4fdd done channel \u5df2\u7ecf\u5173\u95ed\u2014\u2014\u8fd9\u4fdd\u8bc1\u4e86 <code>Err()<\/code> \u548c <code>Done()<\/code> \u7684\u4e00\u81f4\u6027\u3002<\/p>\n<p><strong>3) cancel() \u2014 \u53d6\u6d88\u7684\u6838\u5fc3\u903b\u8f91<\/strong><\/p>\n<pre><code class=\"go\">\/\/ \u6e90\u7801\uff08\u7b80\u5316\u6ce8\u91ca\uff09\nfunc (c *cancelCtx) cancel(removeFromParent bool, err, cause error) {\n    if cause == nil {\n        cause = err\n    }\n    c.mu.Lock()\n    if c.err.Load() != nil {\n        c.mu.Unlock()\n        return \/\/ \u5df2\u7ecf\u53d6\u6d88\u8fc7\u4e86\uff0c\u5e42\u7b49\n    }\n    c.err.Store(err)\n    c.cause = cause\n\n    \/\/ \u5173\u95ed done channel\n    d, _ := c.done.Load().(chan struct{})\n    if d == nil {\n        c.done.Store(closedchan) \/\/ \u590d\u7528\u5168\u5c40\u5df2\u5173\u95ed channel\n    } else {\n        close(d)\n    }\n\n    \/\/ \u9012\u5f52\u53d6\u6d88\u6240\u6709\u5b50 context\n    for child := range c.children {\n        child.cancel(false, err, cause)\n    }\n    c.children = nil\n    c.mu.Unlock()\n\n    if removeFromParent {\n        removeChild(c.Context, c)\n    }\n}<\/code><\/pre>\n<p>\u51e0\u4e2a\u7cbe\u5999\u4e4b\u5904\uff1a<\/p>\n<ul>\n<li><strong>\u5e42\u7b49<\/strong>\uff1a\u591a\u6b21\u8c03\u7528 cancel \u53ea\u6709\u7b2c\u4e00\u6b21\u751f\u6548<\/li>\n<li><strong>closedchan \u590d\u7528<\/strong>\uff1a\u5982\u679c Done() \u4ece\u672a\u88ab\u8c03\u7528\u8fc7\uff08d == nil\uff09\uff0c\u76f4\u63a5\u5b58\u5165\u4e00\u4e2a\u5168\u5c40\u7684\u5df2\u5173\u95ed channel\uff0c\u907f\u514d\u521b\u5efa\u518d\u5173\u95ed<\/li>\n<li><strong>\u9012\u5f52\u53d6\u6d88<\/strong>\uff1a\u904d\u5386 children map\uff0c\u9010\u4e2a\u53d6\u6d88\u5b50 context\u2014\u2014\u8fd9\u5c31\u662f&#8221;\u53d6\u6d88\u5411\u4e0b\u4f20\u64ad&#8221;\u7684\u5b9e\u73b0<\/li>\n<li><strong>\u5148\u53d6\u6d88\u5b50\uff0c\u518d\u4ece\u7236\u79fb\u9664<\/strong>\uff1a\u907f\u514d\u5728\u6301\u6709\u7236\u9501\u65f6\u64cd\u4f5c\u7236\u7684 children map<\/li>\n<\/ul>\n<p><strong>4) propagateCancel() \u2014 \u5efa\u7acb\u7236\u5b50\u5173\u7cfb<\/strong><\/p>\n<pre><code class=\"go\">\/\/ \u6e90\u7801\uff08\u7b80\u5316\uff09\nfunc (c *cancelCtx) propagateCancel(parent Context, child canceler) {\n    c.Context = parent\n\n    done := parent.Done()\n    if done == nil {\n        return \/\/ \u7236 context \u6c38\u8fdc\u4e0d\u4f1a\u53d6\u6d88\uff08\u5982 Background\uff09\uff0c\u65e0\u9700\u4f20\u64ad\n    }\n\n    select {\n    case &lt;-done:\n        child.cancel(false, parent.Err(), Cause(parent))\n        return \/\/ \u7236\u5df2\u53d6\u6d88\uff0c\u7acb\u5373\u53d6\u6d88\u5b50\n    default:\n    }\n\n    if p, ok := parentCancelCtx(parent); ok {\n        \/\/ \u7236\u662f\u6807\u51c6 cancelCtx\uff1a\u76f4\u63a5\u52a0\u5165 children map\uff08\u9ad8\u6548\uff09\n        p.mu.Lock()\n        if err := p.err.Load(); err != nil {\n            child.cancel(false, err.(error), p.cause)\n        } else {\n            if p.children == nil {\n                p.children = make(map[canceler]struct{})\n            }\n            p.children[child] = struct{}{}\n        }\n        p.mu.Unlock()\n    } else if a, ok := parent.(afterFuncer); ok {\n        \/\/ \u7236\u5b9e\u73b0\u4e86 AfterFunc \u63a5\u53e3\uff1a\u7528 AfterFunc \u6ce8\u518c\u53d6\u6d88\u56de\u8c03\n        stop := a.AfterFunc(func() {\n            child.cancel(false, parent.Err(), Cause(parent))\n        })\n        c.Context = stopCtx{Context: parent, stop: stop}\n    } else {\n        \/\/ \u7236\u662f\u81ea\u5b9a\u4e49 Context \u5b9e\u73b0\uff1a\u542f\u52a8 goroutine \u76d1\u542c\n        go func() {\n            select {\n            case &lt;-parent.Done():\n                child.cancel(false, parent.Err(), Cause(parent))\n            case &lt;-child.Done():\n            }\n        }()\n    }\n}<\/code><\/pre>\n<p>\u8fd9\u4e2a\u51fd\u6570\u4f53\u73b0\u4e86 context \u5305\u7684\u5206\u5c42\u4f18\u5316\u7b56\u7565\uff1a<\/p>\n<table>\n<thead>\n<tr>\n<th>\u7236 context \u7c7b\u578b<\/th>\n<th>\u4f20\u64ad\u65b9\u5f0f<\/th>\n<th>\u5f00\u9500<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td><code>Background<\/code>\/<code>TODO<\/code>\uff08Done \u4e3a nil\uff09<\/td>\n<td>\u4e0d\u4f20\u64ad<\/td>\n<td>\u96f6\u5f00\u9500<\/td>\n<\/tr>\n<tr>\n<td>\u6807\u51c6 <code>cancelCtx<\/code><\/td>\n<td>\u52a0\u5165 children map<\/td>\n<td>O(1)\uff0c\u65e0 goroutine<\/td>\n<\/tr>\n<tr>\n<td>\u5b9e\u73b0\u4e86 <code>AfterFunc<\/code> \u63a5\u53e3<\/td>\n<td>\u6ce8\u518c\u56de\u8c03<\/td>\n<td>\u65e0 goroutine<\/td>\n<\/tr>\n<tr>\n<td>\u81ea\u5b9a\u4e49 Context \u5b9e\u73b0<\/td>\n<td>\u542f\u52a8 goroutine \u76d1\u542c<\/td>\n<td>\u4e00\u4e2a goroutine<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>\u7edd\u5927\u591a\u6570\u573a\u666f\u8d70\u7684\u662f\u524d\u4e24\u6761\u8def\u5f84\uff0c\u4e0d\u9700\u8981\u989d\u5916 goroutine\u3002<\/p>\n<h3>9.3 timerCtx \u2014 \u5728 cancelCtx \u4e0a\u52a0\u5b9a\u65f6\u5668<\/h3>\n<pre><code class=\"go\">\/\/ \u6e90\u7801\ntype timerCtx struct {\n    cancelCtx\n    timer    *time.Timer\n    deadline time.Time\n}<\/code><\/pre>\n<p><code>WithDeadline<\/code> \u7684\u6838\u5fc3\u903b\u8f91\uff1a<\/p>\n<pre><code class=\"go\">\/\/ \u6e90\u7801\uff08\u7b80\u5316\uff09\nfunc WithDeadlineCause(parent Context, d time.Time, cause error) (Context, CancelFunc) {\n    \/\/ \u5173\u952e\u4f18\u5316\uff1a\u5982\u679c\u7236\u7684 deadline \u66f4\u65e9\uff0c\u76f4\u63a5\u9000\u5316\u4e3a WithCancel\n    if cur, ok := parent.Deadline(); ok &amp;&amp; cur.Before(d) {\n        return WithCancel(parent)\n    }\n\n    c := &amp;timerCtx{deadline: d}\n    c.cancelCtx.propagateCancel(parent, c)\n\n    dur := time.Until(d)\n    if dur &lt;= 0 {\n        c.cancel(true, DeadlineExceeded, cause) \/\/ \u5df2\u8fc7\u671f\uff0c\u7acb\u5373\u53d6\u6d88\n        return c, func() { c.cancel(false, Canceled, nil) }\n    }\n\n    c.mu.Lock()\n    defer c.mu.Unlock()\n    if c.err.Load() == nil {\n        c.timer = time.AfterFunc(dur, func() {\n            c.cancel(true, DeadlineExceeded, cause)\n        })\n    }\n    return c, func() { c.cancel(true, Canceled, nil) }\n}<\/code><\/pre>\n<p>\u4e24\u4e2a\u91cd\u8981\u4f18\u5316\uff1a<\/p>\n<ul>\n<li><strong>\u7236 deadline \u66f4\u65e9\u65f6\u9000\u5316<\/strong>\uff1a\u5982\u679c\u7236 context \u7684\u622a\u6b62\u65f6\u95f4\u6bd4\u4f60\u8bbe\u7f6e\u7684\u66f4\u65e9\uff0c\u5b50 context \u4e00\u5b9a\u4f1a\u88ab\u7236\u5148\u53d6\u6d88\uff0c\u6240\u4ee5\u6ca1\u5fc5\u8981\u521b\u5efa timer\uff0c\u76f4\u63a5\u9000\u5316\u4e3a <code>WithCancel<\/code><\/li>\n<li><strong>cancel \u65f6\u505c\u6b62 timer<\/strong>\uff1a<code>timerCtx.cancel()<\/code> \u4f1a\u8c03\u7528 <code>c.timer.Stop()<\/code>\uff0c\u8fd9\u5c31\u662f\u4e3a\u4ec0\u4e48 <code>defer cancel()<\/code> \u5f88\u91cd\u8981\u2014\u2014\u5b83\u91ca\u653e\u4e86 timer \u8d44\u6e90<\/li>\n<\/ul>\n<h3>9.4 valueCtx \u4e0e withoutCancelCtx<\/h3>\n<p><strong>valueCtx<\/strong> \u2014 \u6bcf\u4e2a <code>WithValue<\/code> \u53ea\u5b58\u4e00\u4e2a\u952e\u503c\u5bf9\uff0c\u67e5\u627e\u65f6\u6cbf\u94fe\u8868\u5411\u4e0a\u904d\u5386\uff1a<\/p>\n<pre><code class=\"go\">type valueCtx struct {\n    Context\n    key, val any\n}\n\nfunc (c *valueCtx) Value(key any) any {\n    if c.key == key {\n        return c.val\n    }\n    return value(c.Context, key) \/\/ \u5411\u4e0a\u67e5\u627e\n}<\/code><\/pre>\n<p>\u5185\u90e8\u7684 <code>value()<\/code> \u51fd\u6570\u7528 <strong>for \u5faa\u73af\u66ff\u4ee3\u9012\u5f52<\/strong>\uff08\u907f\u514d\u6df1\u5c42\u94fe\u8868\u5bfc\u81f4\u6808\u6ea2\u51fa\uff09\uff0c\u901a\u8fc7 type switch \u9010\u5c42\u5411\u4e0a\u67e5\u627e\u3002\u67e5\u627e\u590d\u6742\u5ea6 O(n)\uff0cn \u662f context \u94fe\u6df1\u5ea6\u2014\u2014\u8fd9\u4e5f\u662f\u4e0d\u5efa\u8bae\u7528 <code>WithValue<\/code> \u5b58\u5927\u91cf\u6570\u636e\u7684\u539f\u56e0\u3002<\/p>\n<p><strong>withoutCancelCtx<\/strong> \u2014 \u7528\u666e\u901a\u5b57\u6bb5 <code>c Context<\/code>\uff08\u800c\u975e\u5d4c\u5165\uff09\u6301\u6709\u7236 context\uff1a<\/p>\n<pre><code class=\"go\">type withoutCancelCtx struct {\n    c Context  \/\/ \u6ce8\u610f\uff1a\u4e0d\u662f\u5d4c\u5165\n}\n\nfunc (withoutCancelCtx) Done() &lt;-chan struct{} { return nil }  \/\/ \u6c38\u4e0d\u53d6\u6d88\nfunc (withoutCancelCtx) Err() error            { return nil }\nfunc (c withoutCancelCtx) Value(key any) any   { return value(c, key) } \/\/ \u4ecd\u7ee7\u627f\u503c<\/code><\/pre>\n<p>\u4e0d\u5d4c\u5165\u610f\u5473\u7740 <code>Done()<\/code> \u548c <code>Deadline()<\/code> \u4e0d\u4f1a\u59d4\u6258\u7ed9\u7236 context\uff0c\u4ece\u800c\u5207\u65ad\u4e86\u53d6\u6d88\u4f20\u64ad\u94fe\uff0c\u540c\u65f6 <code>Value()<\/code> \u4ecd\u80fd\u6cbf\u94fe\u67e5\u627e\u2014\u2014\u8fd9\u5c31\u662f&#8221;\u8131\u79bb\u751f\u547d\u5468\u671f\u4f46\u4fdd\u7559\u4e0a\u4e0b\u6587\u6570\u636e&#8221;\u7684\u5b9e\u73b0\u3002<\/p>\n<h3>9.5 \u8bbe\u8ba1\u542f\u793a<\/h3>\n<p>\u4ece\u6e90\u7801\u4e2d\u53ef\u4ee5\u63d0\u70bc\u51fa\u51e0\u4e2a\u503c\u5f97\u5b66\u4e60\u7684\u8bbe\u8ba1\u6a21\u5f0f\uff1a<\/p>\n<ol>\n<li><strong>\u63a5\u53e3\u5c0f\u800c\u7cbe<\/strong>\uff1a<code>Context<\/code> \u53ea\u6709 4 \u4e2a\u65b9\u6cd5\uff0c\u4f46\u652f\u6491\u4e86\u6574\u4e2a\u5e76\u53d1\u63a7\u5236\u4f53\u7cfb\u3002<code>canceler<\/code> \u5185\u90e8\u63a5\u53e3\u53ea\u6709 2 \u4e2a\u65b9\u6cd5\u3002<\/li>\n<li><strong>\u61d2\u521d\u59cb\u5316<\/strong>\uff1aDone channel \u53ea\u5728\u88ab\u76d1\u542c\u65f6\u624d\u521b\u5efa\uff0cclosedchan \u5168\u5c40\u590d\u7528\u3002<\/li>\n<li><strong>\u5206\u5c42\u4f18\u5316<\/strong>\uff1a<code>propagateCancel<\/code> \u9488\u5bf9\u4e0d\u540c\u7236\u7c7b\u578b\u9009\u62e9\u6700\u4f18\u4f20\u64ad\u7b56\u7565\uff0c\u907f\u514d\u4e0d\u5fc5\u8981\u7684 goroutine\u3002<\/li>\n<li><strong>\u5faa\u73af\u66ff\u4ee3\u9012\u5f52<\/strong>\uff1a<code>value()<\/code> \u51fd\u6570\u7528 for + type switch \u66ff\u4ee3\u9012\u5f52\u8c03\u7528\uff0c\u907f\u514d\u6df1\u5c42\u94fe\u8868\u5bfc\u81f4\u6808\u6ea2\u51fa\u3002<\/li>\n<li><strong>atomic + mutex \u6df7\u7528<\/strong>\uff1a\u70ed\u8def\u5f84\uff08<code>Err()<\/code>\uff09\u7528 atomic\uff0c\u51b7\u8def\u5f84\uff08<code>cancel()<\/code>\uff09\u7528 mutex\uff0c\u5728\u6b63\u786e\u6027\u548c\u6027\u80fd\u95f4\u53d6\u5f97\u5e73\u8861\u3002<\/li>\n<\/ol>\n<h2>\u603b\u7ed3<\/h2>\n<p>context \u5305\u4ece Go 1.7 \u5f15\u5165\u81f3\u4eca\uff08Go 1.26\uff09\uff0c\u5df2\u7ecf\u53d1\u5c55\u4e3a\u4e00\u5957\u5b8c\u6574\u7684\u5e76\u53d1\u63a7\u5236\u5de5\u5177\u96c6\uff08\u5b8c\u6574 API \u89c1<a href=\"https:\/\/segmentfault.com\/a\/#\u5b8c\u6574-api-\u901f\u67e5\u8868\u622a\u81f3-go-126\" target=\"_blank\" rel=\"noopener noreferrer\">\u7b2c\u4e03\u8282\u901f\u67e5\u8868<\/a>\uff09\u3002<\/p>\n<p>\u8bb0\u4f4f\u4e09\u6761\u6838\u5fc3\u539f\u5219\uff1a<\/p>\n<ol>\n<li><strong>context \u662f\u8bf7\u6c42\u7684\u751f\u547d\u7ebf<\/strong> \u2014 \u5b83\u63a7\u5236\u7740\u6574\u68f5 goroutine \u8c03\u7528\u6811\u7684\u751f\u6b7b<\/li>\n<li><strong>\u53d6\u6d88\u5411\u4e0b\u4f20\u64ad<\/strong> \u2014 \u7236\u53d6\u6d88\uff0c\u5b50\u5fc5\u53d6\u6d88\uff1b\u5b50\u53d6\u6d88\uff0c\u7236\u4e0d\u53d7\u5f71\u54cd<\/li>\n<li><strong>\u59cb\u7ec8 defer cancel()<\/strong> \u2014 \u8fd9\u662f\u9632\u6b62\u8d44\u6e90\u6cc4\u6f0f\u7684\u6700\u540e\u4e00\u9053\u9632\u7ebf<\/li>\n<\/ol>\n<p>\u638c\u63e1\u4e86 context\uff0c\u4f60\u5c31\u638c\u63e1\u4e86 Go \u5e76\u53d1\u7f16\u7a0b\u4e2d\u6700\u91cd\u8981\u7684\u534f\u4f5c\u673a\u5236\u3002<\/p>\n<p><a href=\"https:\/\/segmentfault.com\/a\/1190000047682093\">https:\/\/segmentfault.com\/a\/1190000047682093<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>\u524d\u8a00 \u5728 Go \u7684\u5e76\u53d1\u7f16\u7a0b\u4e2d\uff0ccontext \u5305\u662f\u6700\u6838\u5fc3\u7684\u57fa\u7840\u8bbe\u65bd\u4e4b\u4e00\u3002\u5b83\u89e3\u51b3\u4e86\u4e00\u4e2a\u770b\u4f3c\u7b80\u5355\u5374\u6781\u5176\u91cd\u8981\u7684\u95ee\u9898\uff1a [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[4],"tags":[],"class_list":["post-10021331","post","type-post","status-publish","format-standard","hentry","category-share"],"jetpack_sharing_enabled":true,"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/itmax.cn\/index.php?rest_route=\/wp\/v2\/posts\/10021331","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/itmax.cn\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/itmax.cn\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/itmax.cn\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/itmax.cn\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=10021331"}],"version-history":[{"count":0,"href":"https:\/\/itmax.cn\/index.php?rest_route=\/wp\/v2\/posts\/10021331\/revisions"}],"wp:attachment":[{"href":"https:\/\/itmax.cn\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=10021331"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/itmax.cn\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=10021331"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/itmax.cn\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=10021331"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}