日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網(wǎng)站首頁 編程語言 正文

golang的協(xié)程上下文的具體使用_Golang

作者:zhijie ? 更新時間: 2022-06-12 編程語言

go協(xié)程上下文context

golang的context 主要用來在 goroutine 之間傳遞上下文信息,包括:取消信號、超時時間、截止時間、k-v 等

context是golang1.17版本之后才出的特性

上下文解決的問題

  • 協(xié)程間的通信

例如web應用中,每一個請求都由一個協(xié)程去處理。當然處理處理請求的這個協(xié)程,一般我們還會起一些其他的協(xié)程,用來處理其他的業(yè)務,比如操作數(shù)據(jù)庫,生份驗證、文件讀寫等。這些協(xié)程是獨立的,我們在當前的協(xié)程中無法感知到其他的協(xié)程執(zhí)行的情況怎么樣了。實用通道channel可以實現(xiàn)通訊功能

contextcontext.WithValue()本質(zhì)上也是通過channel來實現(xiàn)通訊

  • 子協(xié)程的超時處理

同樣例如web應用當中,我們主進程是一直常駐內(nèi)存的。每一個請求都由一個協(xié)程去處理,在處理業(yè)務的過程中可能會起另外的協(xié)程去處理其他的業(yè)務,當子協(xié)程出現(xiàn)了異常或者阻塞了,無法向上一級的協(xié)程反饋信息,主協(xié)程接受不到反饋也會阻塞。上下文可以很好的解決這個問題,context可以實現(xiàn)子協(xié)程或子孫協(xié)程的超時退出或定時退出

上下文的幾個方法和用法

context.WithCancel(context.Context)

WithCancel()方法傳入一個上下文空實例,直接用context.Background()即可,返回一個上下文和一個取消函數(shù)。調(diào)用cancal()會向其他協(xié)程傳遞信號,收到信號后子協(xié)程就可以做關閉或其他處理

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ù)使用這個上下文,當主協(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ù)使用這個上下文,當主協(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)

原文鏈接:https://juejin.cn/post/7084613288104820773

欄目分類
最近更新