context
主要用于跨多個(gè)Goroutine
設(shè)置截止時(shí)間付枫、同步信號(hào)、傳遞上下文請(qǐng)求值狗热,沒了解過Context的先看看這個(gè)Golang Context 源碼分析
源碼
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package context defines the Context type, which carries deadlines,
// cancellation signals, and other request-scoped values across API boundaries
// and between processes.
//
// Incoming requests to a server should create a Context, and outgoing
// calls to servers should accept a Context. The chain of function
// calls between them must propagate the Context, optionally replacing
// it with a derived Context created using WithCancel, WithDeadline,
// WithTimeout, or WithValue. When a Context is canceled, all
// Contexts derived from it are also canceled.
//
// The WithCancel, WithDeadline, and WithTimeout functions take a
// Context (the parent) and return a derived Context (the child) and a
// CancelFunc. Calling the CancelFunc cancels the child and its
// children, removes the parent's reference to the child, and stops
// any associated timers. Failing to call the CancelFunc leaks the
// child and its children until the parent is canceled or the timer
// fires. The go vet tool checks that CancelFuncs are used on all
// control-flow paths.
//
// Programs that use Contexts should follow these rules to keep interfaces
// consistent across packages and enable static analysis tools to check context
// propagation:
//
// Do not store Contexts inside a struct type; instead, pass a Context
// explicitly to each function that needs it. The Context should be the first
// parameter, typically named ctx:
//
// func DoSomething(ctx context.Context, arg Arg) error {
// // ... use ctx ...
// }
//
// Do not pass a nil Context, even if a function permits it. Pass context.TODO
// if you are unsure about which Context to use.
//
// Use context Values only for request-scoped data that transits processes and
// APIs, not for passing optional parameters to functions.
//
// The same Context may be passed to functions running in different goroutines;
// Contexts are safe for simultaneous use by multiple goroutines.
//
// See https://blog.golang.org/context for example code for a server that uses
// Contexts.
package context
import (
"errors"
"internal/reflectlite"
"sync"
"sync/atomic"
"time"
)
// A Context carries a deadline, a cancellation signal, and other values across
// API boundaries.
//
// Context's methods may be called by multiple goroutines simultaneously.
// Context接口定義了四個(gè)方法
type Context interface {
// Deadline returns the time when work done on behalf of this context
// should be canceled. Deadline returns ok==false when no deadline is
// set. Successive calls to Deadline return the same results.
// 獲取截止時(shí)間
Deadline() (deadline time.Time, ok bool)
// Done returns a channel that's closed when work done on behalf of this
// context should be canceled. Done may return nil if this context can
// never be canceled. Successive calls to Done return the same value.
// The close of the Done channel may happen asynchronously,
// after the cancel function returns.
//
// WithCancel arranges for Done to be closed when cancel is called;
// WithDeadline arranges for Done to be closed when the deadline
// expires; WithTimeout arranges for Done to be closed when the timeout
// elapses.
//
// Done is provided for use in select statements:
//
// // Stream generates values with DoSomething and sends them to out
// // until DoSomething returns an error or ctx.Done is closed.
// func Stream(ctx context.Context, out chan<- Value) error {
// for {
// v, err := DoSomething(ctx)
// if err != nil {
// return err
// }
// select {
// case <-ctx.Done():
// return ctx.Err()
// case out <- v:
// }
// }
// }
//
// See https://blog.golang.org/pipelines for more examples of how to use
// a Done channel for cancellation.
// 獲取信號(hào)通道钞馁,用于判斷父Context是否已取消
// <-chan struct{} 這里struct{}是常用的占位手法,不占用內(nèi)存空間
// 因?yàn)槭侵蛔x通道匿刮,當(dāng)該通道關(guān)閉時(shí)僧凰,所有的子Context就可以結(jié)合select來及時(shí)獲得通知,從而達(dá)到層層廣播的效果熟丸,類似多米諾骨牌
Done() <-chan struct{}
// If Done is not yet closed, Err returns nil.
// If Done is closed, Err returns a non-nil error explaining why:
// Canceled if the context was canceled
// or DeadlineExceeded if the context's deadline passed.
// After Err returns a non-nil error, successive calls to Err return the same error.
// 通道取消的錯(cuò)誤信息允悦,用于區(qū)分是哪種原因取消了
Err() error
// Value returns the value associated with this context for key, or nil
// if no value is associated with key. Successive calls to Value with
// the same key returns the same result.
//
// Use context values only for request-scoped data that transits
// processes and API boundaries, not for passing optional parameters to
// functions.
//
// A key identifies a specific value in a Context. Functions that wish
// to store values in Context typically allocate a key in a global
// variable then use that key as the argument to context.WithValue and
// Context.Value. A key can be any type that supports equality;
// packages should define keys as an unexported type to avoid
// collisions.
//
// Packages that define a Context key should provide type-safe accessors
// for the values stored using that key:
//
// // Package user defines a User type that's stored in Contexts.
// package user
//
// import "context"
//
// // User is the type of value stored in the Contexts.
// type User struct {...}
//
// // key is an unexported type for keys defined in this package.
// // This prevents collisions with keys defined in other packages.
// type key int
//
// // userKey is the key for user.User values in Contexts. It is
// // unexported; clients use user.NewContext and user.FromContext
// // instead of using this key directly.
// var userKey key
//
// // NewContext returns a new Context that carries value u.
// func NewContext(ctx context.Context, u *User) context.Context {
// return context.WithValue(ctx, userKey, u)
// }
//
// // FromContext returns the User value stored in ctx, if any.
// func FromContext(ctx context.Context) (*User, bool) {
// u, ok := ctx.Value(userKey).(*User)
// return u, ok
// }
// 獲取key對(duì)應(yīng)的value值
Value(key interface{}) interface{}
}
// Canceled is the error returned by Context.Err when the context is canceled.
var Canceled = errors.New("context canceled")
// DeadlineExceeded is the error returned by Context.Err when the context's
// deadline passes.
var DeadlineExceeded error = deadlineExceededError{}
type deadlineExceededError struct{}
func (deadlineExceededError) Error() string { return "context deadline exceeded" }
func (deadlineExceededError) Timeout() bool { return true }
func (deadlineExceededError) Temporary() bool { return true }
// An emptyCtx is never canceled, has no values, and has no deadline. It is not
// struct{}, since vars of this type must have distinct addresses.
// 空的context
// 不會(huì)過期,沒有截止時(shí)間虑啤,沒有<k, v>
type emptyCtx int
func (*emptyCtx) Deadline() (deadline time.Time, ok bool) {
return
}
func (*emptyCtx) Done() <-chan struct{} {
return nil
}
func (*emptyCtx) Err() error {
return nil
}
func (*emptyCtx) Value(key interface{}) interface{} {
return nil
}
func (e *emptyCtx) String() string {
switch e {
case background:
return "context.Background"
case todo:
return "context.TODO"
}
return "unknown empty Context"
}
var (
background = new(emptyCtx)
todo = new(emptyCtx)
)
// Background returns a non-nil, empty Context. It is never canceled, has no
// values, and has no deadline. It is typically used by the main function,
// initialization, and tests, and as the top-level Context for incoming
// requests.
// 空Context的別名隙弛,用于構(gòu)造所有context的根
func Background() Context {
return background
}
// TODO returns a non-nil, empty Context. Code should use context.TODO when
// it's unclear which Context to use or it is not yet available (because the
// surrounding function has not yet been extended to accept a Context
// parameter).
// 空Context的別名,用于占位
// 比如你現(xiàn)在不知道要傳什么context狞山,就可以用TODO來占位
func TODO() Context {
return todo
}
// A CancelFunc tells an operation to abandon its work.
// A CancelFunc does not wait for the work to stop.
// A CancelFunc may be called by multiple goroutines simultaneously.
// After the first call, subsequent calls to a CancelFunc do nothing.
// 定義取消操作
type CancelFunc func()
// WithCancel returns a copy of parent with a new Done channel. The returned
// context's Done channel is closed when the returned cancel function is called
// or when the parent context's Done channel is closed, whichever happens first.
//
// Canceling this context releases resources associated with it, so code should
// call cancel as soon as the operations running in this Context complete.
// 構(gòu)建可取消的Context
func WithCancel(parent Context) (ctx Context, cancel CancelFunc) {
// 父Context不能為nil全闷,這也為什么要對(duì)外提供Background的原因
if parent == nil {
panic("cannot create context from nil parent")
}
// 新建一個(gè)cancelCtx
c := newCancelCtx(parent)
// 將新建的cancelCtx向上掛靠到最近的可取消父Context
// 對(duì)于WithCancel來說,這里有一個(gè)隱藏約定萍启,就是所有的可取消的Context的Done()方法返回的channel都不會(huì)是nil总珠,而所有不可取消的都是nil
propagateCancel(parent, &c)
// 返回Context和對(duì)應(yīng)的cancel方法
return &c, func() { c.cancel(true, Canceled) }
}
// newCancelCtx returns an initialized cancelCtx.
// 新建并返回cancelCtx
func newCancelCtx(parent Context) cancelCtx {
return cancelCtx{Context: parent}
}
// goroutines counts the number of goroutines ever created; for testing.
// 測(cè)試用例使用,不用關(guān)心
var goroutines int32
// propagateCancel arranges for child to be canceled when parent is.
// 掛靠可取消父Context
// 該方法接受兩個(gè)接口類型的參數(shù)勘纯,一個(gè)是Context局服,一個(gè)是canceler
// 因?yàn)槿∠鸆ontext的方式有多種,目前context包默認(rèn)實(shí)現(xiàn)了兩種
// canceler接口包含了不可導(dǎo)出的cancel方法驳遵,所以用戶是無法自己實(shí)現(xiàn)canceler接口的
// 所以該方法接收canceler接口類型而不是具體的結(jié)構(gòu)體比如cancelCtx
func propagateCancel(parent Context, child canceler) {
// 獲取父Context的取消通道
// 因?yàn)镃ontext以組合的方式來層層嵌套
// 所以調(diào)用Done()方法也會(huì)逆序?qū)訉訖z查并調(diào)用
// 當(dāng)done == nil的時(shí)候淫奔,說明整個(gè)Context樹都沒有可取消的Context (上面說的約定)
done := parent.Done()
if done == nil {
return // parent is never canceled
}
// 這里判斷parent是否已經(jīng)取消,如果取消堤结,則立刻調(diào)用child的cancel方法執(zhí)行對(duì)應(yīng)取消操作
select {
case <-done:
// parent is already canceled
// 注意這里傳的第一個(gè)參數(shù)是false唆迁,代表不需要從parent的child集合中刪除該child鸭丛,理由很簡(jiǎn)單唐责,因?yàn)檫€沒掛靠上去
// 具體可見cancel方法的實(shí)現(xiàn)
child.cancel(false, parent.Err())
return
default:
}
// 是否找到可掛靠的cancelCtx
// 這里需要做區(qū)分鳞溉,如果是cancelCtx或者cancelCtx的包裝類型且沒有重寫更改Done()和Value()方法和對(duì)應(yīng)的動(dòng)作,就可以通過child集合的方式進(jìn)行掛靠
// 否則就只能起個(gè)協(xié)程鼠哥,以監(jiān)聽通道信號(hào)的方式進(jìn)行掛靠
if p, ok := parentCancelCtx(parent); ok {
// 加鎖
// 這里加鎖粒度要注意熟菲,因?yàn)榭紤]并發(fā)情況,判斷p.err的時(shí)候就需要加鎖朴恳,而且p.err設(shè)置只可能是在取消的時(shí)候且必須加鎖科盛,這里一旦加了鎖,那么p.err就無法被設(shè)置菜皂,也就無法變更了
p.mu.Lock()
if p.err != nil {
// parent has already been canceled
child.cancel(false, p.err)
} else {
if p.children == nil {
// 延遲初始化,同時(shí)對(duì)p.children的讀寫操作都要加鎖
// 這里又是struct{}的妙用厉萝,通過map實(shí)現(xiàn)了集合
p.children = make(map[canceler]struct{})
}
p.children[child] = struct{}{}
}
p.mu.Unlock()
} else {
// 什么情況下認(rèn)為有可取消Context但是沒找到cancelCtx呢
// 當(dāng)用戶自定義Done()或者Value()并且改變了原來的行為時(shí)恍飘,可能就會(huì)導(dǎo)致,具體看后面例子
atomic.AddInt32(&goroutines, +1) //測(cè)試用的谴垫,不用關(guān)心
go func() { // 開個(gè)協(xié)程章母,監(jiān)聽父Context和自己的取消信號(hào)
select {
case <-parent.Done():
child.cancel(false, parent.Err())
case <-child.Done(): //這里也要監(jiān)聽自己的,因?yàn)橛锌赡躢hild自動(dòng)取消了翩剪,比如定時(shí)器Context
}
}()
}
}
// &cancelCtxKey is the key that a cancelCtx returns itself for.
// 這是一個(gè)標(biāo)識(shí)乳怎,用于復(fù)用Value()方法來找到cancelCtx
// 注意這是一個(gè)不可導(dǎo)出的變量
var cancelCtxKey int
// parentCancelCtx returns the underlying *cancelCtx for parent.
// It does this by looking up parent.Value(&cancelCtxKey) to find
// the innermost enclosing *cancelCtx and then checking whether
// parent.Done() matches that *cancelCtx. (If not, the *cancelCtx
// has been wrapped in a custom implementation providing a
// different done channel, in which case we should not bypass it.)
// 找到父cancelCtx
func parentCancelCtx(parent Context) (*cancelCtx, bool) {
// 獲得信號(hào)通道
done := parent.Done()
// 這里沒有像propagateCancel方法使用select來判斷是否關(guān)閉,也沒有執(zhí)行cancel操作前弯,這個(gè)會(huì)向上拋給propagateCancel方法蚪缀,通過case <-parent.Done():來操作cancel
// 因?yàn)檫@里明確就是找到cancelCtx,而cancelCtx一旦取消了恕出,done肯定就是closedchan
// 而且這里又判斷了一次done == nil是因?yàn)檫€有removeChild方法調(diào)用了該方法
if done == closedchan || done == nil {
return nil, false
}
// 只有cancelCtx實(shí)現(xiàn)的Value方法询枚,才能通過Value(&cancelCtxKey)拿到自身
p, ok := parent.Value(&cancelCtxKey).(*cancelCtx)
if !ok {
return nil, false
}
// 這里需要做進(jìn)一步判斷,因?yàn)橥ㄟ^value找到的Context的Done()方法可能被用戶自定義覆蓋了浙巫,這就不能按照cancelCtx來處理金蜀,因?yàn)槠鋵?duì)應(yīng)的cancel操作是會(huì)操作cancelCtx.done的,而這個(gè)done跟Done()方法返回的可能不是同一個(gè)的畴,就會(huì)造成取消行為的歧義
// 同時(shí)加了一把鎖
p.mu.Lock()
ok = p.done == done
p.mu.Unlock()
if !ok {
return nil, false
}
return p, true
}
// removeChild removes a context from its parent.
// 從parent的child集合中刪除自己
func removeChild(parent Context, child canceler) {
// 找到之前掛載的父Context
p, ok := parentCancelCtx(parent)
if !ok {
return
}
// 修改行為渊抄,加鎖
p.mu.Lock()
// 有可能在加鎖之前,父Context執(zhí)行了取消丧裁,p.children == nil
if p.children != nil {
delete(p.children, child)
}
p.mu.Unlock()
}
// A canceler is a context type that can be canceled directly. The
// implementations are *cancelCtx and *timerCtx.
// 取消接口
// 注意這里定義的cancel方法是不可導(dǎo)出的护桦,不支持用戶自定義
type canceler interface {
cancel(removeFromParent bool, err error)
Done() <-chan struct{}
}
// closedchan is a reusable closed channel.
// 可重用的已關(guān)閉的channel
var closedchan = make(chan struct{})
// init()方法,關(guān)閉closedchan
// 該方法在調(diào)用其他方法之前已執(zhí)行
func init() {
close(closedchan)
}
// A cancelCtx can be canceled. When canceled, it also cancels any children
// that implement canceler.
// 可取消Context
type cancelCtx struct {
Context
mu sync.Mutex // protects following fields
done chan struct{} // created lazily, closed by first cancel call
children map[canceler]struct{} // set to nil by the first cancel call
err error // set to non-nil by the first cancel call
}
func (c *cancelCtx) Value(key interface{}) interface{} {
// 還記得吧煎娇,這個(gè)特殊的cancelCtxKey可以用來標(biāo)記返回自身
if key == &cancelCtxKey {
return c
}
return c.Context.Value(key)
}
func (c *cancelCtx) Done() <-chan struct{} {
// 常規(guī)加鎖操作
c.mu.Lock()
// 這里會(huì)延遲初始化嘶炭,主要是為了將done的初始化包裝到cancelCtx的方法中抱慌,這樣就算用戶包裝了cancelCtx,也能觸發(fā)done的初始化
if c.done == nil {
c.done = make(chan struct{})
}
d := c.done
c.mu.Unlock()
return d
}
// 錯(cuò)誤處理眨猎,不細(xì)說
func (c *cancelCtx) Err() error {
c.mu.Lock()
err := c.err
c.mu.Unlock()
return err
}
// 下面三個(gè)方法都是為了支持打印操作抑进,不細(xì)說
type stringer interface {
String() string
}
func contextName(c Context) string {
if s, ok := c.(stringer); ok {
return s.String()
}
return reflectlite.TypeOf(c).String()
}
func (c *cancelCtx) String() string {
return contextName(c.Context) + ".WithCancel"
}
// cancel closes c.done, cancels each of c's children, and, if
// removeFromParent is true, removes c from its parent's children.
// cancelCtx的取消操作
func (c *cancelCtx) cancel(removeFromParent bool, err error) {
// 必須要有取消信息
if err == nil {
panic("context: internal error: missing cancel error")
}
c.mu.Lock()
// 已經(jīng)取消過了
if c.err != nil {
c.mu.Unlock()
return // already canceled
}
c.err = err
// 還未初始化的done,就給一個(gè)已關(guān)閉的channel
if c.done == nil {
c.done = closedchan
} else {
close(c.done)
}
// 取消所有的子Context
for child := range c.children {
// NOTE: acquiring the child's lock while holding parent's lock.
child.cancel(false, err)
}
c.children = nil
c.mu.Unlock()
// 是否從父Context的child集合中刪除自己
if removeFromParent {
removeChild(c.Context, c)
}
}
// WithDeadline returns a copy of the parent context with the deadline adjusted
// to be no later than d. If the parent's deadline is already earlier than d,
// WithDeadline(parent, d) is semantically equivalent to parent. The returned
// context's Done channel is closed when the deadline expires, when the returned
// cancel function is called, or when the parent context's Done channel is
// closed, whichever happens first.
//
// Canceling this context releases resources associated with it, so code should
// call cancel as soon as the operations running in this Context complete.
// 對(duì)cancelCtx的包裝睡陪,支持截止時(shí)間
func WithDeadline(parent Context, d time.Time) (Context, CancelFunc) {
if parent == nil {
panic("cannot create context from nil parent")
}
// 如果父Context的截止時(shí)間比當(dāng)前截止時(shí)間更早寺渗,那直接作為cancelCtx掛著就行了
if cur, ok := parent.Deadline(); ok && cur.Before(d) {
// The current deadline is already sooner than the new one.
return WithCancel(parent)
}
c := &timerCtx{
cancelCtx: newCancelCtx(parent),
deadline: d,
}
// 將c掛靠到可取消的父Context
propagateCancel(parent, c)
dur := time.Until(d)
// 如果到了截止時(shí)間
if dur <= 0 {
c.cancel(true, DeadlineExceeded) // deadline has already passed
return c, func() { c.cancel(false, Canceled) }
}
// 這里要加鎖,因?yàn)橐坏炜苛死计龋涂赡鼙挥|發(fā)cancel操作
c.mu.Lock()
defer c.mu.Unlock()
// 如果沒有被觸發(fā)取消
if c.err == nil {
// 啟一個(gè)定時(shí)器信殊,一旦到點(diǎn)就會(huì)執(zhí)行func(),也就是cancel操作
c.timer = time.AfterFunc(dur, func() {
c.cancel(true, DeadlineExceeded)
})
}
return c, func() { c.cancel(true, Canceled) }
}
// A timerCtx carries a timer and a deadline. It embeds a cancelCtx to
// implement Done and Err. It implements cancel by stopping its timer then
// delegating to cancelCtx.cancel.
type timerCtx struct {
cancelCtx
timer *time.Timer // Under cancelCtx.mu.
deadline time.Time
}
// 獲取截止時(shí)間
func (c *timerCtx) Deadline() (deadline time.Time, ok bool) {
return c.deadline, true
}
func (c *timerCtx) String() string {
return contextName(c.cancelCtx.Context) + ".WithDeadline(" +
c.deadline.String() + " [" +
time.Until(c.deadline).String() + "])"
}
// timerCtx的cancel操作
func (c *timerCtx) cancel(removeFromParent bool, err error) {
// 注意這里是false汁果,因?yàn)閽炜康氖前b的timerCtx
c.cancelCtx.cancel(false, err)
if removeFromParent {
// Remove this timerCtx from its parent cancelCtx's children.
removeChild(c.cancelCtx.Context, c)
}
c.mu.Lock()
// 停掉定時(shí)器
if c.timer != nil {
c.timer.Stop()
c.timer = nil
}
c.mu.Unlock()
}
// WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)).
//
// Canceling this context releases resources associated with it, so code should
// call cancel as soon as the operations running in this Context complete:
//
// func slowOperationWithTimeout(ctx context.Context) (Result, error) {
// ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)
// defer cancel() // releases resources if slowOperation completes before timeout elapses
// return slowOperation(ctx)
// }
// WithDeadline的包裝恨锚,支持超時(shí)時(shí)間段
func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) {
return WithDeadline(parent, time.Now().Add(timeout))
}
// WithValue returns a copy of parent in which the value associated with key is
// val.
//
// Use context Values only for request-scoped data that transits processes and
// APIs, not for passing optional parameters to functions.
//
// The provided key must be comparable and should not be of type
// string or any other built-in type to avoid collisions between
// packages using context. Users of WithValue should define their own
// types for keys. To avoid allocating when assigning to an
// interface{}, context keys often have concrete type
// struct{}. Alternatively, exported context key variables' static
// type should be a pointer or interface.
// 傳遞<k,v>的Context
func WithValue(parent Context, key, val interface{}) Context {
if parent == nil {
panic("cannot create context from nil parent")
}
if key == nil {
panic("nil key")
}
// 注意必須是可比較的類型脚粟,slice、map和函數(shù)是不可以的
if !reflectlite.TypeOf(key).Comparable() {
panic("key is not comparable")
}
return &valueCtx{parent, key, val}
}
// A valueCtx carries a key-value pair. It implements Value for that key and
// delegates all other calls to the embedded Context.
type valueCtx struct {
Context
key, val interface{}
}
// stringify tries a bit to stringify v, without using fmt, since we don't
// want context depending on the unicode tables. This is only used by
// *valueCtx.String().
func stringify(v interface{}) string {
switch s := v.(type) {
case stringer:
return s.String()
case string:
return s
}
return "<not Stringer>"
}
func (c *valueCtx) String() string {
return contextName(c.Context) + ".WithValue(type " +
reflectlite.TypeOf(c.key).String() +
", val " + stringify(c.val) + ")"
}
// 獲取<k,v>
func (c *valueCtx) Value(key interface{}) interface{} {
if c.key == key {
return c.val
}
// 這里會(huì)層層解套調(diào)用父Context的Value()方法來實(shí)現(xiàn)全遍歷
return c.Context.Value(key)
}
使用建議
以下是來自官方的使用Context的建議,比較好讀筹淫,不翻譯了
- Contexts inside a struct type; instead, pass a Context explicitly to each function that needs it. The Context should be the first parameter, typically named ctx.
- Do not pass a nil Context, even if a function permits it. Pass context.TODO if you are unsure about which Context to use.
- Use context Values only for request-scoped data that transits processes and APIs, not for passing optional parameters to functions.
- The same Context may be passed to functions running in different goroutines; Contexts are safe for simultaneous use by multiple goroutines.
舉個(gè)栗子
WithValue
func main() {
ctx := context.WithValue(context.Background(), 1, 1)
ctx = withName(ctx)
WithValueTest(ctx)
}
func withName(ctx context.Context) context.Context {
return context.WithValue(ctx, "name", "joker")
}
func WithValueTest(ctx context.Context) {
fmt.Println(ctx.Value(1).(int)) // 1
fmt.Println(ctx.Value("name").(string)) // joker
v, ok := ctx.Value("no-set").(int)
fmt.Println(v, ok) // 0 false
}
注意担映,這只是個(gè)用法示例持痰,實(shí)際使用中Context傳遞的應(yīng)該是作用于整個(gè)請(qǐng)求的數(shù)據(jù)修陡,比如request_id,token之類的善玫,自定義的數(shù)據(jù)盡量通過參數(shù)傳遞水援,否則當(dāng)Context嵌套層數(shù)一多,你自己可能都搞不清楚傳了哪些茅郎,哪些節(jié)點(diǎn)能獲取到哪些數(shù)據(jù)
WithCancel
func main() {
ctx, cancel := context.WithCancel(context.Background())
go handler(ctx)
time.Sleep(time.Second * 3)
cancel()
time.Sleep(time.Second * 2)
}
func handler(ctx context.Context) {
for {
select {
case <-ctx.Done():
fmt.Println("handler canceled")
return
default:
fmt.Println("handler running")
time.Sleep(time.Second)
}
}
}
// output
handler running
handler running
handler running
handler running
handler canceled
WithTimeout
func main() {
ctx, _ := context.WithTimeout(context.Background(), time.Second * 2)
go handler(ctx)
time.Sleep(time.Second * 4)
}
func handler(ctx context.Context) {
for {
select {
case <-ctx.Done():
fmt.Println("handler canceled")
return
default:
fmt.Println("handler running")
time.Sleep(time.Second)
}
}
}
// output
handler running
handler running
handler canceled
總結(jié)
context
解決了并發(fā)控制的問題蜗元,但是設(shè)計(jì)上面并不夠優(yōu)雅,需要所有涉及到的方法/函數(shù)層層傳遞Context類型參數(shù)系冗,而且對(duì)于Value()方法的實(shí)現(xiàn)许帐,是遞歸的鏈?zhǔn)教幚恚阅懿皇呛芎帽锨矗沂褂玫姆秶邢蕹善瑁瑢?duì)初學(xué)者很容易誤用濫用導(dǎo)致后期維護(hù)困難