Go 上下文 context 底層原理
1. context 介紹
很多時候,我們會遇到這樣的情況,上層與下層的 goroutine 需要同時取消,這樣就涉及到了 goroutine 間的通信。在 Go 中,推薦我們以通信的方式共享內存,而不是以共享內存的方式通信。
所以,就需要用到 channl,但是,在上述場景中,如果需要自己去處理 channl 的業務邏輯,就會有很多費時費力的重複工作,因此,context 出現了。
context 是 Go 中用來進程通信的一種方式,其底層是藉助channl
與snyc.Mutex
實現的。
2. 基本介紹
context
的底層設計,我們可以概括爲 1 個接口,4 種實現與 6 個方法。
-
1 個接口
- Context 規定了
context
的四個基本方法
- Context 規定了
-
4 種實現
-
emptyCtx 實現了一個空的
context
,可以用作根節點 -
cancelCtx 實現一個帶
cancel
功能的context
,可以主動取消 -
timerCtx 實現一個通過定時器
timer
和截止時間deadline
定時取消的context
-
valueCtx 實現一個可以通過
key、val
兩個字段來存數據的context
-
-
6 個方法
-
Background 返回一個
emptyCtx
作爲根節點 -
TODO 返回一個
emptyCtx
作爲未知節點 -
WithCancel 返回一個
cancelCtx
-
WithDeadline 返回一個
timerCtx
-
WithTimeout 返回一個
timerCtx
-
WithValue 返回一個
valueCtx
-
3. 源碼分析
3.1 Context 接口
type Context interface {
Deadline() (deadline time.Time, ok bool)
Done() <-chan struct{}
Err() error
Value(key interface{}) interface{}
}
-
Deadline() :返回一個 time.Time,表示當前 Context 應該結束的時間,ok 則表示有結束時間
-
Done():返回一個只讀 chan,如果可以從該 chan 中讀取到數據,則說明 ctx 被取消了
-
Err():返回 Context 被取消的原因
-
Value(key):返回 key 對應的 value,是協程安全的
3.2 emptyCtx
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
}
emptyCtx
實現了空的Context
接口,其主要作用是爲Background
和TODO
這兩個方法都會返回預先初始化好的私有變量 background
和 todo
,它們會在同一個 Go 程序中被複用:
var (
background = new(emptyCtx)
todo = new(emptyCtx)
)
func Background() Context {
return background
}
func TODO() Context {
return todo
}
Background
和TODO
在實現上沒有區別,只是在使用語義上有所差異:
-
Background
是上下文的根節點; -
TODO
應該僅在不確定應該使用哪種上下文時使用;
3.3 cancelCtx
cancelCtx
實現了canceler
接口與Context
接口:
type canceler interface {
cancel(removeFromParent bool, err error)
Done() <-chan struct{}
}
其結構體如下:
type cancelCtx struct {
// 直接嵌入了一個 Context,那麼可以把 cancelCtx 看做是一個 Context
Context
mu sync.Mutex // protects following fields
done atomic.Value // of 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
}
我們可以使用WithCancel
的方法來創建一個cancelCtx
:
func WithCancel(parent Context) (ctx Context, cancel CancelFunc) {
if parent == nil {
panic("cannot create context from nil parent")
}
c := newCancelCtx(parent)
propagateCancel(parent, &c)
return &c, func() { c.cancel(true, Canceled) }
}
func newCancelCtx(parent Context) cancelCtx {
return cancelCtx{Context: parent}
}
上面的方法,我們傳入一個父 Context(這通常是一個 background
,作爲根節點),返回新建的 context,並通過閉包的形式,返回了一個 cancel 方法。
newCancelCtx
將傳入的上下文包裝成私有結構體context.cancelCtx
。
propagateCancel
則會構建父子上下文之間的關聯,形成樹結構,當父上下文被取消時,子上下文也會被取消:
func propagateCancel(parent Context, child canceler) {
// 1.如果 parent ctx 是不可取消的 ctx,則直接返回 不進行關聯
done := parent.Done()
if done == nil {
return // parent is never canceled
}
// 2.接着判斷一下 父ctx 是否已經被取消
select {
case <-done:
// 2.1 如果 父ctx 已經被取消了,那就沒必要關聯了
// 然後這裏也要順便把子ctx給取消了,因爲父ctx取消了 子ctx就應該被取消
// 這裏是因爲還沒有關聯上,所以需要手動觸發取消
// parent is already canceled
child.cancel(false, parent.Err())
return
default:
}
// 3. 從父 ctx 中提取出 cancelCtx 並將子ctx加入到父ctx 的 children 裏面
if p, ok := parentCancelCtx(parent); ok {
p.mu.Lock()
// double check 一下,確認父 ctx 是否被取消
if p.err != nil {
// 取消了就直接把當前這個子ctx給取消了
// parent has already been canceled
child.cancel(false, p.err)
} else {
// 否則就添加到 children 裏面
if p.children == nil {
p.children = make(map[canceler]struct{})
}
p.children[child] = struct{}{}
}
p.mu.Unlock()
} else {
// 如果沒有找到可取消的父 context。新啓動一個協程監控父節點或子節點取消信號
atomic.AddInt32(&goroutines, +1)
go func() {
select {
case <-parent.Done():
child.cancel(false, parent.Err())
case <-child.Done():
}
}()
}
}
上面的方法可能遇到以下幾種情況:
-
當
parent.Done() == nil
,也就是parent
不會觸發取消事件時,當前函數會直接返回; -
當
child
的繼承鏈包含可以取消的上下文時,會判斷parent
是否已經觸發了取消信號; -
如果已經被取消,
child
會立刻被取消; -
如果沒有被取消,
child
會被加入parent
的children
列表中,等待parent
釋放取消信號; -
當父上下文是開發者自定義的類型、實現了 context.Context 接口並在
Done()
方法中返回了非空的管道時; -
運行一個新的 Goroutine 同時監聽
parent.Done()
和child.Done()
兩個 Channel; -
在
parent.Done()
關閉時調用child.cancel
取消子上下文;
propagateCancel
的作用是在 parent
和 child
之間同步取消和結束的信號,保證在 parent
被取消時,child
也會收到對應的信號,不會出現狀態不一致的情況。
func parentCancelCtx(parent Context) (*cancelCtx, bool) {
done := parent.Done()
// 如果 done 爲 nil 說明這個ctx是不可取消的
// 如果 done == closedchan 說明這個ctx不是標準的 cancelCtx,可能是自定義的
if done == closedchan || done == nil {
return nil, false
}
// 然後調用 value 方法從ctx中提取出 cancelCtx
p, ok := parent.Value(&cancelCtxKey).(*cancelCtx)
if !ok {
return nil, false
}
// 最後再判斷一下cancelCtx 裏存的 done 和 父ctx裏的done是否一致
// 如果不一致說明parent不是一個 cancelCtx
pdone, _ := p.done.Load().(chan struct{})
if pdone != done {
return nil, false
}
return p, true
}
cancelCtx 的 done 方法會返回一個 chan struct{}
:
func (c *cancelCtx) Done() <-chan struct{} {
d := c.done.Load()
if d != nil {
return d.(chan struct{})
}
c.mu.Lock()
defer c.mu.Unlock()
d = c.done.Load()
if d == nil {
d = make(chan struct{})
c.done.Store(d)
}
return d.(chan struct{})
}
var closedchan = make(chan struct{})
parentCancelCtx 其實就是判斷 parent context 裏面有沒有一個 cancelCtx,有就返回,讓子 context 可以 “掛靠” 到 parent context 上,如果不是就返回 false,不進行掛靠,自己新開一個 goroutine 來監聽。
3.4 timerCtx
timerCtx 內部不僅通過嵌入 cancelCtx 的方式承了相關的變量和方法,還通過持有的定時器 timer
和截止時間 deadline
實現了定時取消的功能:
type timerCtx struct {
cancelCtx
timer *time.Timer // Under cancelCtx.mu.
deadline time.Time
}
func (c *timerCtx) Deadline() (deadline time.Time, ok bool) {
return c.deadline, true
}
func (c *timerCtx) cancel(removeFromParent bool, err error) {
c.cancelCtx.cancel(false, err)
if removeFromParent {
removeChild(c.cancelCtx.Context, c)
}
c.mu.Lock()
if c.timer != nil {
c.timer.Stop()
c.timer = nil
}
c.mu.Unlock()
}
3.5 valueCtx
valueCtx 是多了 key、val 兩個字段來存數據:
type valueCtx struct {
Context
key, val interface{}
}
取值查找的過程,實際上是一個遞歸查找的過程:
func (c *valueCtx) Value(key interface{}) interface{} {
if c.key == key {
return c.val
}
return c.Context.Value(key)
}
如果 key 和當前 ctx 中存的 value 一致就直接返回,沒有就去 parent 中找。最終找到根節點(一般是 emptyCtx),直接返回一個 nil。所以用 Value 方法的時候要判斷結果是否爲 nil,類似於一個鏈表,效率是很低的,不建議用來傳參數。
4. 使用建議
在官方博客裏,對於使用 context 提出了幾點建議:
-
不要將 Context 塞到結構體裏。直接將 Context 類型作爲函數的第一參數,而且一般都命名爲 ctx。
-
不要向函數傳入一個 nil 的 context,如果你實在不知道傳什麼,標準庫給你準備好了一個 context:todo。
-
不要把本應該作爲函數參數的類型塞到 context 中,context 存儲的應該是一些共同的數據。例如:登陸的 session、cookie 等。
-
同一個 context 可能會被傳遞到多個 goroutine,別擔心,context 是併發安全的。
轉自:
https://juejin.cn/post/7106157600399425543
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/fkvfrfJyvav30VcYwPeG9Q