取消有关上下文取消的进一步操作

我有一个接收上下文并执行一些cpu绑定操作(如波纹管)的func。

func DoSomeOperation(ctx context.Context){
    CPUBoundWork1()
    CPUBoundWork2()
    CPUBoundWork3()
    CPUBoundWork4()
}

我想做的是在进行每个CPUBound调用之前检查是否已取消。如果取消,我想立即返回,而无需制作下一个功能。有什么办法可以做到这一点吗?Contextfunccall


ibeautiful
浏览 112回答 1
1回答

温温酱

使用 ctx。错误()if ctx.Err() == context.Canceled {&nbsp; &nbsp; return}您也可以将 select 语句与 的一起使用。slicefunctions例如:&nbsp; &nbsp; ctx := ...&nbsp; &nbsp; executors := []func(){...}Loop:&nbsp; &nbsp; for _,executor := range executors{&nbsp; &nbsp; &nbsp; &nbsp; select {&nbsp; &nbsp; &nbsp; &nbsp; case <-ctx.Done():&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if ctx.Err() == context.Canceled {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break Loop&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if ctx.Err() == context.DeadlineExceeded {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //do something else&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; default:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; executor()&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go