成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

一文吃透 Go 語言解密之上下文 Context

開發 后端
上下文(Context)是 Go 語言中非常有特色的一個特性, 在 Go 1.7 版本中正式引入新標準庫 context。

[[378300]]

大家好,我是煎魚。

上下文(Context)是 Go 語言中非常有特色的一個特性, 在 Go 1.7 版本中正式引入新標準庫 context。

其主要的作用是在 goroutine 中進行上下文的傳遞,而在傳遞信息中又包含了 goroutine 的運行控制、上下文信息傳遞等功能。

 

為加強大家對 Go 語言的 context 的設計,本文將對標準庫 context 進行深入剖析,看看他里面到底暗含了何物,又為何能夠做那么多事。

整體的描述結構是:“了解 context 特性,熟悉 context 流程,剖析 context 原理” 三個板塊進行。目錄如下:

 

什么是 context

Go 語言的獨有的功能之一 Context,最常聽說開發者說的一句話就是 “函數的第一個形參真的要傳 ctx 嗎?”,第二句話可能是 “有沒有什么辦法不傳,就能達到傳入的效果?”,聽起來非常魔幻。

在 Go 語言中 context 作為一個 “一等公民” 的標準庫,許多的開源庫都一定會對他進行支持,因為標準庫 context 的定位是上下文控制。會在跨 goroutine 中進行傳播:

 

本質上 Go 語言是基于 context 來實現和搭建了各類 goroutine 控制的,并且與 select-case聯合,就可以實現進行上下文的截止時間、信號控制、信息傳遞等跨 goroutine 的操作,是 Go 語言協程的重中之重。

context 基本特性

演示代碼:

  1. func main() { 
  2.  parentCtx := context.Background() 
  3.  ctx, cancel := context.WithTimeout(parentCtx, 1*time.Millisecond) 
  4.  defer cancel() 
  5.  
  6.  select { 
  7.  case <-time.After(1 * time.Second): 
  8.   fmt.Println("overslept"
  9.  case <-ctx.Done(): 
  10.   fmt.Println(ctx.Err()) 
  11.  } 

輸出結果:

  1. context deadline exceeded 

我們通過調用標準庫 context.WithTimeout 方法針對 parentCtx 變量設置了超時時間,并在隨后調用 select-case 進行 context.Done 方法的監聽,最后由于達到截止時間。因此邏輯上 select 走到了 context.Err 的 case 分支,最終輸出 context deadline exceeded。

除了上述所描述的方法外,標準庫 context 還支持下述方法:

  1. func WithCancel(parent Context) (ctx Context, cancel CancelFunc) 
  2. func WithDeadline(parent Context, d time.Time) (Context, CancelFunc) 
  3. func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) 
  4. type Context 
  5.     func Background() Context 
  6.     func TODO() Context 
  7.     func WithValue(parent Context, key, val interface{}) Context 
  • WithCancel:基于父級 context,創建一個可以取消的新 context。
  • WithDeadline:基于父級 context,創建一個具有截止時間(Deadline)的新 context。
  • WithTimeout:基于父級 context,創建一個具有超時時間(Timeout)的新 context。
  • Background:創建一個空的 context,一般常用于作為根的父級 context。
  • TODO:創建一個空的 context,一般用于未確定時的聲明使用。
  • WithValue:基于某個 context 創建并存儲對應的上下文信息。

context 本質

我們在基本特性中介紹了不少 context 的方法,其基本大同小異。看上去似乎不難,接下來我們看看其底層的基本原理和設計。

context 相關函數的標準返回如下:

  1. func WithXXXX(parent Context, xxx xxx) (Context, CancelFunc) 

其返回值分別是 Context 和 CancelFunc,接下來我們將進行分析這兩者的作用。

接口

1. Context 接口:

  1. type Context interface { 
  2.     Deadline() (deadline time.Time, ok bool) 
  3.     Done() <-chan struct{} 
  4.     Err() error 
  5.     Value(key interface{}) interface{} 
  • Deadline:獲取當前 context 的截止時間。
  • Done:獲取一個只讀的 channel,類型為結構體。可用于識別當前 channel 是否已經被關閉,其原因可能是到期,也可能是被取消了。
  • Err:獲取當前 context 被關閉的原因。
  • Value:獲取當前 context 對應所存儲的上下文信息。

2. Canceler 接口:

  1. type canceler interface { 
  2.  cancel(removeFromParent bool, err error) 
  3.  Done() <-chan struct{} 
  • cancel:調用當前 context 的取消方法。
  • Done:與前面一致,可用于識別當前 channel 是否已經被關閉。

基礎結構

在標準庫 context 的設計上,一共提供了四類 context 類型來實現上述接口。分別是 emptyCtx、cancelCtx、timerCtx 以及 valueCtx。

 

emptyCtx

在日常使用中,常常使用到的 context.Background 方法,又或是 context.TODO 方法。

源碼如下:

  1. var ( 
  2.  background = new(emptyCtx) 
  3.  todo       = new(emptyCtx) 
  4.  
  5. func Background() Context { 
  6.  return background 
  7.  
  8. func TODO() Context { 
  9.  return todo 

其本質上都是基于 emptyCtx 類型的基本封裝。而 emptyCtx 類型本質上是實現了 Context 接口:

  1. type emptyCtx int 
  2.  
  3. func (*emptyCtx) Deadline() (deadline time.Time, ok bool) { 
  4.  return 
  5.  
  6. func (*emptyCtx) Done() <-chan struct{} { 
  7.  return nil 
  8.  
  9. func (*emptyCtx) Err() error { 
  10.  return nil 
  11.  
  12. func (*emptyCtx) Value(key interface{}) interface{} { 
  13.  return nil 

實際上 emptyCtx 類型的 context 的實現非常簡單,因為他是空 context 的定義,因此沒有 deadline,更沒有 timeout,可以認為就是一個基礎空白 context 模板。

cancelCtx

在調用 context.WithCancel 方法時,我們會涉及到 cancelCtx 類型,其主要特性是取消事件。源碼如下:

  1. func WithCancel(parent Context) (ctx Context, cancel CancelFunc) { 
  2.  c := newCancelCtx(parent) 
  3.  propagateCancel(parent, &c) 
  4.  return &c, func() { c.cancel(true, Canceled) } 
  5.  
  6. func newCancelCtx(parent Context) cancelCtx { 
  7.  return cancelCtx{Context: parent} 

其中的 newCancelCtx 方法將會生成出一個可以取消的新 context,如果該 context 執行取消,與其相關聯的子 context 以及對應的 goroutine 也會收到取消信息。

首先 main goroutine 創建并傳遞了一個新的 context 給 goroutine b,此時 goroutine b 的 context 是 main goroutine context 的子集:

 

傳遞過程中,goroutine b 再將其 context 一個個傳遞給了 goroutine c、d、e。最后在運行時 goroutine b 調用了 cancel 方法。使得該 context 以及其對應的子集均接受到取消信號,對應的 goroutine 也進行了響應。

接下來我們針對 cancelCtx 類型來進一步看看:

  1. type cancelCtx struct { 
  2.  Context 
  3.  
  4.  mu       sync.Mutex            // protects following fields 
  5.  done     chan struct{}         // created lazily, closed by first cancel call 
  6.  children map[canceler]struct{} // set to nil by the first cancel call 
  7.  err      error                 // set to non-nil by the first cancel call 

該結構體所包含的屬性也比較簡單,主要是 children 字段,其包含了該 context 對應的所有子集 context,便于在后續發生取消事件的時候進行逐一通知和關聯。

而其他的屬性主要用于并發控制(互斥鎖)、取消信息和錯誤的寫入:

  1. func (c *cancelCtx) Value(key interface{}) interface{} { 
  2.  if key == &cancelCtxKey { 
  3.   return c 
  4.  } 
  5.  return c.Context.Value(key
  6.  
  7. func (c *cancelCtx) Done() <-chan struct{} { 
  8.  c.mu.Lock() 
  9.  if c.done == nil { 
  10.   c.done = make(chan struct{}) 
  11.  } 
  12.  d := c.done 
  13.  c.mu.Unlock() 
  14.  return d 
  15.  
  16. func (c *cancelCtx) Err() error { 
  17.  c.mu.Lock() 
  18.  err := c.err 
  19.  c.mu.Unlock() 
  20.  return err 

在上述代碼中可以留意到,done 屬性(只讀 channel)是在真正調用到 Done 方法時才會去創建。需要配合 select-case 來使用。

timerCtx

在調用 context.WithTimeout 方法時,我們會涉及到 timerCtx 類型,其主要特性是 Timeout 和 Deadline 事件,源碼如下:

  1. func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) { 
  2.  return WithDeadline(parent, time.Now().Add(timeout)) 
  3.  
  4. func WithDeadline(parent Context, d time.Time) (Context, CancelFunc) { 
  5.  ... 
  6.  c := &timerCtx{ 
  7.   cancelCtx: newCancelCtx(parent), 
  8.   deadline:  d, 
  9.  } 

你可以發現 timerCtx 類型是基于 cancelCtx 類型的。我們再進一步看看 timerCtx 結構體:

  1. type timerCtx struct { 
  2.  cancelCtx 
  3.  timer *time.Timer // Under cancelCtx.mu. 
  4.  
  5.  deadline time.Time 

其實 timerCtx 類型也就是 cancelCtx 類型,加上 time.Timer 和對應的 Deadline,也就是包含了時間屬性的控制。

我們進一步看看其配套的 cancel 方法,思考一下其是如何進行取消動作的:

  1. func (c *timerCtx) Deadline() (deadline time.Time, ok bool) { 
  2.  return c.deadline, true 
  3.  
  4. func (c *timerCtx) cancel(removeFromParent bool, err error) { 
  5.  c.cancelCtx.cancel(false, err) 
  6.  if removeFromParent { 
  7.   removeChild(c.cancelCtx.Context, c) 
  8.  } 
  9.  c.mu.Lock() 
  10.  if c.timer != nil { 
  11.   c.timer.Stop() 
  12.   c.timer = nil 
  13.  } 
  14.  c.mu.Unlock() 

先會調用 cancelCtx 類型的取消事件。若存在父級節點,則移除當前 context 子節點,最后停止定時器并進行定時器重置。而 Deadline 或 Timeout 的行為則由 timerCtx 的 WithDeadline 方法實現:

  1. func WithDeadline(parent Context, d time.Time) (Context, CancelFunc) { 
  2.  if cur, ok := parent.Deadline(); ok && cur.Before(d) { 
  3.   // The current deadline is already sooner than the new one. 
  4.   return WithCancel(parent) 
  5.  } 
  6.  ... 

該方法會先進行前置判斷,若父級節點的 Deadline 時間早于當前所指定的 Deadline 時間,將會直接生成一個 cancelCtx 的 context。

  1. func WithDeadline(parent Context, d time.Time) (Context, CancelFunc) { 
  2.  ... 
  3.  c := &timerCtx{ 
  4.   cancelCtx: newCancelCtx(parent), 
  5.   deadline:  d, 
  6.  } 
  7.  propagateCancel(parent, c) 
  8.  dur := time.Until(d) 
  9.  if dur <= 0 { 
  10.   c.cancel(true, DeadlineExceeded) // deadline has already passed 
  11.   return c, func() { c.cancel(false, Canceled) } 
  12.  } 
  13.  c.mu.Lock() 
  14.  defer c.mu.Unlock() 
  15.  if c.err == nil { 
  16.   c.timer = time.AfterFunc(dur, func() { 
  17.    c.cancel(true, DeadlineExceeded) 
  18.   }) 
  19.  } 
  20.  return c, func() { c.cancel(true, Canceled) } 

接下來將會正式生成成為一個 timeCtx 類型,并將其加入到父級 context 是 children 屬性中。最后進行當前時間與 Deadline 時間的計算,并通過調用 time.AfterFunc 在到期后自動調用 cancel 方法發起取消事件,自然也就會觸發父子級的事件傳播。

valueCtx

在調用 context.WithValue 方法時,我們會涉及到 valueCtx 類型,其主要特性是涉及上下文信息傳遞,源碼如下:

  1. func WithValue(parent Context, key, val interface{}) Context { 
  2.  ... 
  3.  if !reflectlite.TypeOf(key).Comparable() { 
  4.   panic("key is not comparable"
  5.  } 
  6.  return &valueCtx{parent, key, val} 

你會發現 valueCtx 結構體也非常的簡單,核心就是鍵值對:

  1. type valueCtx struct { 
  2.  Context 
  3.  key, val interface{} 

其在配套方法上也不會太復雜,基本就是要求可比較,接著就是存儲匹配:

  1. func (c *valueCtx) Value(key interface{}) interface{} { 
  2.  if c.key == key { 
  3.   return c.val 
  4.  } 
  5.  return c.Context.Value(key

這時候你可能又有疑問了,那多個父子級 context 是如何實現跨 context 的上下文信息獲取的?

這秘密其實在上面的 valueCtx 和 Value 方法中有所表現:

 

本質上 valueCtx 類型是一個單向鏈表,會在調用 Value 方法時先查詢自己的節點是否有該值。若無,則會通過自身存儲的上層父級節點的信息一層層向上尋找對應的值,直到找到為止。

而在實際的工程應用中,你會發現各大框架,例如:gin、grpc 等。他都是有自己再實現一套上下文信息的傳輸的二次封裝,本意也是為了更好的管理和觀察上下文信息。

context 取消事件

在我們針對 context 的各類延伸類型和源碼進行了分析后。我們進一步提出一個疑問點,context 是如何實現跨 goroutine 的取消事件并傳播開來的,是如何實現的?

這個問題的答案就在于 WithCancel 和 WithDeadline 都會涉及到 propagateCancel 方法,其作用是構建父子級的上下文的關聯關系,若出現取消事件時,就會進行處理:

  1. func propagateCancel(parent Context, child canceler) { 
  2.  done := parent.Done() 
  3.  if done == nil { 
  4.   return 
  5.  } 
  6.  
  7.  select { 
  8.  case <-done: 
  9.   child.cancel(false, parent.Err()) 
  10.   return 
  11.  default
  12.  } 
  13.  ... 
  • 當父級上下文(parent)的 Done 結果為 nil 時,將會直接返回,因為其不會具備取消事件的基本條件,可能該 context 是 Background、TODO 等方法產生的空白 context。
  • 當父級上下文(parent)的 Done 結果不為 nil 時,則發現父級上下文已經被取消,作為其子級,該 context 將會觸發取消事件并返回父級上下文的取消原因。
  1. func propagateCancel(parent Context, child canceler) { 
  2.  ... 
  3.  if p, ok := parentCancelCtx(parent); ok { 
  4.   p.mu.Lock() 
  5.   if p.err != nil { 
  6.    child.cancel(false, p.err) 
  7.   } else { 
  8.    if p.children == nil { 
  9.     p.children = make(map[canceler]struct{}) 
  10.    } 
  11.    p.children[child] = struct{}{} 
  12.   } 
  13.   p.mu.Unlock() 
  14.  } else { 
  15.   atomic.AddInt32(&goroutines, +1) 
  16.   go func() { 
  17.    select { 
  18.    case <-parent.Done(): 
  19.     child.cancel(false, parent.Err()) 
  20.    case <-child.Done(): 
  21.    } 
  22.   }() 
  23.  } 

經過前面一個代碼片段的判斷,已得知父級 context 未觸發取消事件,當前父級和子級 context 均正常(未取消)。

將會執行以下流程:

  • 調用 parentCancelCtx 方法找到具備取消功能的父級 context。并將當前 context,也就是 child 加入到 父級 context 的 children 列表中,等待后續父級 context 的取消事件通知和響應。
  • 調用 parentCancelCtx 方法沒有找到,將會啟動一個新的 goroutine 去監聽父子 context 的取消事件通知。

通過對 context 的取消事件和整體源碼分析,可得知 cancelCtx 類型的上下文包含了其下屬的所有子節點信息:

 

也就是其在 children 屬性的 map[canceler]struct{} 存儲結構上就已經支持了子級關系的查找,也就自然可以進行取消事件傳播了。

而具體的取消事件的實際行為,則是在前面提到的 propagateCancel 方法中,會在執行例如cacenl 方法時,會對父子級上下文分別進行狀態判斷,若滿足則進行取消事件,并傳播給子級同步取消。

總結

作為 Go 語言的核心功能之一,其實標準庫 context 非常的短小精悍,使用的都是基本的數據結構和理念。既滿足了跨 goroutine 的調控控制,像是并發、超時控制等。

同時也滿足了上下文的信息傳遞。在工程應用中,例如像是鏈路ID、公共參數、鑒權校驗等,都會使用到 context 作為媒介。

目前官方對于 context 的建議是作為方法的首參數傳入,雖有些麻煩,但也有人選擇將其作為結構體中的一個屬性傳入。但這也會帶來一些心智負擔,需要識別是否重新 new 一個。

也有人提出希望 Go2 取消掉 context,換成另外一種方法,但總體而言目前未見到正式的提案,這是我們都需要再思考的。

 

責任編輯:武曉燕 來源: 腦子進煎魚了
相關推薦

2025-03-18 09:10:00

MCPAI模型上下文協議

2025-01-08 11:10:46

2022-10-28 16:24:33

Context上下文鴻蒙

2025-04-07 05:01:00

MCP上下文協議LLM?

2022-05-03 21:01:10

架構項目映射

2025-04-07 01:02:00

GoAPI語言

2017-05-11 14:00:02

Flask請求上下文應用上下文

2024-08-27 09:46:39

Go協程效率

2015-10-09 09:43:28

CSS CSS3

2024-04-26 00:01:00

Go語言類型

2021-07-26 07:47:36

Cpu上下文進程

2012-12-31 10:01:34

SELinuxSELinux安全

2022-09-14 13:13:51

JavaScript上下文

2022-11-03 08:29:32

編程管理器協議

2025-02-08 09:13:40

2021-04-27 11:28:21

React.t事件元素

2024-09-18 13:57:15

2024-12-03 12:02:05

2022-09-15 08:01:14

繼承基礎設施基礎服務

2023-11-01 08:08:50

Go語言傳遞請求
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 久久一区二区三区四区 | 成人欧美一区二区三区色青冈 | 亚洲黄色av | 粉嫩一区二区三区性色av | 日韩免费福利视频 | 欧美日韩中文在线观看 | 日韩一区二区三区在线 | 亚洲精品福利视频 | 福利影院在线看 | 日本一道本视频 | 青青久久| 青青草视频网站 | 91精品国产91久久综合桃花 | 日本色高清 | 久久久成人精品 | 国产精品一区在线观看 | 久久黄色 | 亚州精品天堂中文字幕 | 国产一区二 | 久久精品国产一区二区电影 | 99九九久久| 黄色网页在线 | 91在线看视频 | 日韩一区二区三区精品 | 精品国产一区二区在线 | 国产福利在线视频 | 亚洲欧美在线观看 | 欧美一区二区成人 | 69电影网| 久久精品色欧美aⅴ一区二区 | 日韩一区二区在线免费观看 | 欧美午夜精品 | 波多野结衣在线观看一区二区三区 | 国产小视频在线观看 | 国产精品一区久久久久 | 国产美女精品视频免费观看 | 日韩三级在线 | 99re6在线视频精品免费 | 人人看人人草 | 日韩爱爱网 | 在线成人av|