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

學無先后,達者為師

網站首頁 編程語言 正文

golang的協程上下文的具體使用_Golang

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

go協程上下文context

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

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

上下文解決的問題

  • 協程間的通信

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

contextcontext.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

欄目分類
最近更新