golang的協(xié)程上下文的具體使用
go協(xié)程上下文context
golang的context 主要用來在 goroutine 之間傳遞上下文信息,包括:取消信號、超時時間、截止時間、k-v 等
context是golang1.17版本之后才出的特性
上下文解決的問題
- 協(xié)程間的通信
例如web應(yīng)用中,每一個請求都由一個協(xié)程去處理。當(dāng)然處理處理請求的這個協(xié)程,一般我們還會起一些其他的協(xié)程,用來處理其他的業(yè)務(wù),比如操作數(shù)據(jù)庫,生份驗證、文件讀寫等。這些協(xié)程是獨立的,我們在當(dāng)前的協(xié)程中無法感知到其他的協(xié)程執(zhí)行的情況怎么樣了。實用通道channel可以實現(xiàn)通訊功能
context中context.WithValue()本質(zhì)上也是通過channel來實現(xiàn)通訊
- 子協(xié)程的超時處理
同樣例如web應(yīng)用當(dāng)中,我們主進(jìn)程是一直常駐內(nèi)存的。每一個請求都由一個協(xié)程去處理,在處理業(yè)務(wù)的過程中可能會起另外的協(xié)程去處理其他的業(yè)務(wù),當(dāng)子協(xié)程出現(xiàn)了異?;蛘咦枞耍瑹o法向上一級的協(xié)程反饋信息,主協(xié)程接受不到反饋也會阻塞。上下文可以很好的解決這個問題,context可以實現(xiàn)子協(xié)程或子孫協(xié)程的超時退出或定時退出
上下文的幾個方法和用法
context.WithCancel(context.Context)
WithCancel()方法傳入一個上下文空實例,直接用context.Background()即可,返回一個上下文和一個取消函數(shù)。調(diào)用cancal()會向其他協(xié)程傳遞信號,收到信號后子協(xié)程就可以做關(guān)閉或其他處理
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)
定義一個會超時的上下文,實例化后倒計時就開始,到時間會自動調(diào)用cancel()函數(shù)通知子協(xié)程,也可以手動調(diào)用cancel()通知。如果子協(xié)程中還有子協(xié)程,繼續(xù)使用這個上下文,當(dāng)主協(xié)程發(fā)出取消信號時每一個使用了這個上下文的都會收到通知
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不同在于,傳入的時間是一個絕對時間。到了指定的時間會自動調(diào)用cancel()函數(shù)通知子協(xié)程,也可以手動調(diào)用cancel()通知。如果子協(xié)程中還有子協(xié)程,繼續(xù)使用這個上下文,當(dāng)主協(xié)程發(fā)出取消信號時每一個使用了這個上下文的都會收到通知
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 ...")
?
}協(xié)程間的上下文通訊:context.WithValue()
先看一下這段代碼
package main
?
import (
"context"
"fmt"
"time"
)
?
type CTXKEY string
?
func worker(ctx context.Context) {
// 在子協(xié)程中獲取上下文信息
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 ...")
}通過上下文實現(xiàn)協(xié)程間的通信,如果項目大,為了避免變量的污染,原則上:上下文通信所用的key需要自定義一個類型
type traceCode string;context.WithValue(context.Context,key,value)
到此這篇關(guān)于golang的協(xié)程上下文的文章就介紹到這了,更多相關(guān)golang的協(xié)程上下文內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
go語言題解LeetCode453最小操作次數(shù)使數(shù)組元素相等
這篇文章主要為大家介紹了go語言題解LeetCode453最小操作次數(shù)使數(shù)組元素相等示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12

