第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

有沒有辦法在一個 goroutine 返回后延遲后取消上下文?

有沒有辦法在一個 goroutine 返回后延遲后取消上下文?

Go
精慕HU 2022-12-05 17:28:24
問題情況我目前有一個 gin 處理函數(shù),它使用相同的上下文在三個獨立的 goroutine 中運行三個獨立的查詢。有一個錯誤組 ( "golang.org/x/sync/errgroup") 使用此共享上下文,處理程序在返回之前等待錯誤組??陀^的我試圖實現(xiàn)的行為是在一個 goroutines 完成后,應(yīng)該對剩余的 goroutines 強制執(zhí)行超時,但是如果 gin 請求被取消(連接關(guān)閉),這個上下文也應(yīng)該被取消,這意味著 ginctx.Request.Context()必須使用。潛在的解決方案當(dāng)前實施目前,我有一個超時傳遞給 errgroup 的上下文,但這只是對所有 goroutines 強制執(zhí)行超時。timeoutCtx := context.WithTimeout(context.Background(), 10*time.Second)g, err := errgroup.WithContext(timeoutCtx)g.Go(func1)g.Go(func2)g.Go(func3)err = g.Wait()需要使用 gin 請求上下文,這樣如果連接關(guān)閉并且請求被取消,goroutines 也會停止。// ctx *gin.Contextg, err := errgroup.WithContext(ctx.Request.Context())g.Go(func1)g.Go(func2)g.Go(func3)err = g.Wait()
查看完整描述

1 回答

?
叮當(dāng)貓咪

TA貢獻1776條經(jīng)驗 獲得超12個贊

請注意context.WithTimeout()

  • 可以包裝任何上下文(不僅僅是context.Background()

  • 也返回一個cancel函數(shù)

您可以在上面添加超時ctx.Request.Context(),并cancel在任何查詢完成時調(diào)用:

timeoutCtx, cancel := context.WithTimeout(ctx.Request.Context())


g, err := errgroup.WithContext(timeoutCtx)


g.Go( func1(cancel) ) // pass the cancel callback to each query some way or another

g.Go( func2(cancel) ) // you prabably want to also pass timeoutCtx

g.Go( func3(cancel) )


g.Wait()

根據(jù)您的評論:還有context.WithCancel(),您可以在延遲后調(diào)用取消


childCtx, cancel := context.WithCancel(ctx.Request.Context())


g, err := errgroup.WithContext(childCtx)


hammerTime := func(){

    <-time.After(1*time.Second)

    cancel()

}


g.Go( func1(hammerTime) ) // funcXX should have access to hammerTime

g.Go( func2(hammerTime) )

g.Go( func3(hammerTime) )


g.Wait()


查看完整回答
反對 回復(fù) 2022-12-05
  • 1 回答
  • 0 關(guān)注
  • 115 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號