網站首頁 編程語言 正文
go協程上下文context
golang的context
主要用來在 goroutine 之間傳遞上下文信息,包括:取消信號、超時時間、截止時間、k-v 等
context
是golang1.17
版本之后才出的特性
上下文解決的問題
- 協程間的通信
例如web應用中,每一個請求都由一個協程去處理。當然處理處理請求的這個協程,一般我們還會起一些其他的協程,用來處理其他的業務,比如操作數據庫,生份驗證、文件讀寫等。這些協程是獨立的,我們在當前的協程中無法感知到其他的協程執行的情況怎么樣了。實用通道channel
可以實現通訊功能
context
中context.WithValue()
本質上也是通過channel
來實現通訊
- 子協程的超時處理
同樣例如web應用當中,我們主進程是一直常駐內存的。每一個請求都由一個協程去處理,在處理業務的過程中可能會起另外的協程去處理其他的業務,當子協程出現了異常或者阻塞了,無法向上一級的協程反饋信息,主協程接受不到反饋也會阻塞。上下文可以很好的解決這個問題,context
可以實現子協程或子孫協程的超時退出或定時退出
上下文的幾個方法和用法
context.WithCancel(context.Context)
WithCancel()
方法傳入一個上下文空實例,直接用context.Background()
即可,返回一個上下文和一個取消函數。調用cancal()
會向其他協程傳遞信號,收到信號后子協程就可以做關閉或其他處理
package main ? import ( "context" "fmt" "time" ) func worker(ctx context.Context) { for { select { case <-ctx.Done(): return default: } fmt.Println("worker...") time.Sleep(time.Second * 1) } } func main() { ctx, cancal := context.WithCancel(context.Background()) go worker(ctx) time.Sleep(time.Second * 5) cancal() fmt.Println("over ...") ? }
context.WithTimeout(context.Context,timeout)
定義一個會超時的上下文,實例化后倒計時就開始,到時間會自動調用cancel()
函數通知子協程,也可以手動調用cancel()
通知。如果子協程中還有子協程,繼續使用這個上下文,當主協程發出取消信號時每一個使用了這個上下文的都會收到通知
package main ? import ( "context" "fmt" "time" ) ? func worker(ctx context.Context) { for { select { case <-ctx.Done(): return default: } fmt.Println("worker...") time.Sleep(time.Second * 1) } } ? func main() { ctx, cancal := context.WithTimeout(context.Background(), time.Second*2) go worker(ctx) time.Sleep(time.Second * 5) cancal() fmt.Println("over ...") ? }
context.WithDeadline(context.Context,(絕對時間)timeout)
定義一個會超時的上下文,與Timeout
不同在于,傳入的時間是一個絕對時間。到了指定的時間會自動調用cancel()
函數通知子協程,也可以手動調用cancel()
通知。如果子協程中還有子協程,繼續使用這個上下文,當主協程發出取消信號時每一個使用了這個上下文的都會收到通知
package main ? import ( "context" "fmt" "time" ) ? func worker(ctx context.Context) { for { select { case <-ctx.Done(): return default: } fmt.Println("worker...") time.Sleep(time.Second * 1) } } ? func main() { ctx, cancal := context.WithDeadline(context.Background(), time.Now().Add(3 * time.Second)) go worker(ctx) time.Sleep(time.Second * 5) cancal() fmt.Println("over ...") ? }
協程間的上下文通訊:context.WithValue()
先看一下這段代碼
package main ? import ( "context" "fmt" "time" ) ? type CTXKEY string ? func worker(ctx context.Context) { // 在子協程中獲取上下文信息 num, ok := ctx.Value(CTXKEY("num")).(string) if !ok { fmt.Println("invalid trace code") } fmt.Println(num) for { select { case <-ctx.Done(): return default: } fmt.Println("worker...") time.Sleep(time.Second * 1) } } ? func main() { ctx, cancal := context.WithDeadline(context.Background(), time.Now().Add(3*time.Second)) // 利用上下文傳一個 num = 1234567 // 實例化一個上下文 ctx = context.WithValue(ctx, CTXKEY("num"), "1234567") go worker(ctx) time.Sleep(time.Second * 5) cancal() fmt.Println("over ...") }
通過上下文實現協程間的通信,如果項目大,為了避免變量的污染,原則上:上下文通信所用的key需要自定義一個類型
type traceCode string;context.WithValue(context.Context,key,value)
原文鏈接:https://juejin.cn/post/7084613288104820773
相關推薦
- 2022-04-15 React+Node實現大文件分片上傳、斷點續傳秒傳思路_React
- 2022-10-18 Qt?TCP實現簡單通信功能_C 語言
- 2022-10-21 Go?Ticker?周期性定時器用法及實現原理詳解_Golang
- 2023-04-29 C/C++并查集的查詢與合并實現原理_C 語言
- 2023-10-16 textarea文本編輯器改變字體顏色
- 2024-01-29 SpringBoot的自動裝配原理
- 2023-05-22 關于PyTorch中nn.Module類的簡介_python
- 2022-12-07 python?yield迭代器詳解_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支