如何使用context.Context在函数调用链中取消

时间:2018-10-25 19:26:23

标签: go

假设我具有以下功能:

func A(ctx context.Context) {
    // A takes some time to process
}

func B(ctx context.Context) {
    // B takes some time to process
}

func C(ctx context.Context) {
    // C takes some time to process
}

注意:每个函数调用都需要一些时间来处理。

注意:B应该在函数A内部调用,C应该在函数B内部调用。

仅需要针对这种特定情况的示例。

1 个答案:

答案 0 :(得分:1)

您只需传递与参数相同的上下文,但是每当您从channel \ remote server \中等待结果时,只要使用<< ctx.Done(),就使用select语句。每当上下文被取消(通过取消功能或由于超时)时,内部通道将被关闭,并且接收操作始终在关闭的通道上解除阻塞。

有关取消的一般文章(无上下文,但在精神上用ctx.Done()替换doneCh) https://blog.golang.org/pipelines

谈论取消(第15页的上下文示例) https://talks.golang.org/2014/gotham-context.slide#15

例子 https://www.sohamkamani.com/blog/golang/2018-06-17-golang-using-context-cancellation/