1 回答

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()
- 1 回答
- 0 關(guān)注
- 115 瀏覽
添加回答
舉報