context.go

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ù)困難

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市涝开,隨后出現(xiàn)的幾起案子循帐,更是在濱河造成了極大的恐慌,老刑警劉巖舀武,帶你破解...
    沈念sama閱讀 216,372評(píng)論 6 498
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件拄养,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)瘪匿,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,368評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門跛梗,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人棋弥,你說我怎么就攤上這事核偿。” “怎么了顽染?”我有些...
    開封第一講書人閱讀 162,415評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵漾岳,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我粉寞,道長(zhǎng)尼荆,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,157評(píng)論 1 292
  • 正文 為了忘掉前任唧垦,我火速辦了婚禮捅儒,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘振亮。我一直安慰自己巧还,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,171評(píng)論 6 388
  • 文/花漫 我一把揭開白布双炕。 她就那樣靜靜地躺著,像睡著了一般撮抓。 火紅的嫁衣襯著肌膚如雪妇斤。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,125評(píng)論 1 297
  • 那天丹拯,我揣著相機(jī)與錄音站超,去河邊找鬼。 笑死乖酬,一個(gè)胖子當(dāng)著我的面吹牛死相,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播咬像,決...
    沈念sama閱讀 40,028評(píng)論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼算撮,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了县昂?” 一聲冷哼從身側(cè)響起肮柜,我...
    開封第一講書人閱讀 38,887評(píng)論 0 274
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎倒彰,沒想到半個(gè)月后审洞,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,310評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡待讳,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,533評(píng)論 2 332
  • 正文 我和宋清朗相戀三年芒澜,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了仰剿。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,690評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡痴晦,死狀恐怖南吮,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情阅酪,我是刑警寧澤旨袒,帶...
    沈念sama閱讀 35,411評(píng)論 5 343
  • 正文 年R本政府宣布,位于F島的核電站术辐,受9級(jí)特大地震影響砚尽,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜辉词,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,004評(píng)論 3 325
  • 文/蒙蒙 一必孤、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧瑞躺,春花似錦敷搪、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,659評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至捞镰,卻和暖如春闸与,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背岸售。 一陣腳步聲響...
    開封第一講書人閱讀 32,812評(píng)論 1 268
  • 我被黑心中介騙來泰國(guó)打工践樱, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人凸丸。 一個(gè)月前我還...
    沈念sama閱讀 47,693評(píng)論 2 368
  • 正文 我出身青樓拷邢,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親屎慢。 傳聞我的和親對(duì)象是個(gè)殘疾皇子瞭稼,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,577評(píng)論 2 353