Go 上下文取消函数的最佳实践

Best practices on go context cancelation functions

我一直在阅读一些关于使用 golang 的上下文包的文章。我最近在博客中看到了以下文章:http://p.agnihotry.com/post/understanding_the_context_package_in_golang/

这篇文章对 go 中的上下文取消函数做了如下说明:

"You can pass around the cancel function if you wanted to, but, that is highly not recommended. This can lead to the invoker of cancel not realizing what the downstream impact of canceling the context may be. There may be other contexts that are derived from this which may cause the program to behave in an unexpected fashion. In short, NEVER pass around the cancel function."

但是,如果我希望父 context.Done() 通道被激活,将取消函数作为参数传递似乎是唯一的选择(参见下面的代码片段)。例如,下面代码片段中的代码完成通道仅在执行函数 2 时激活。

package main

import (
    "context"
    "fmt"
    "time"
)

func function1(ctx context.Context) {
    _, cancelFunction := context.WithCancel(ctx)
    fmt.Println("cancel called from function1")
    cancelFunction()
}

func function2(ctx context.Context, cancelFunction context.CancelFunc) {
    fmt.Println("cancel called from function2")
    cancelFunction()
}

func main() {
    //Make a background context
    ctx := context.Background()
    //Derive a context with cancel
    ctxWithCancel, cancelFunction := context.WithCancel(ctx)

    go function1(ctxWithCancel)
    time.Sleep(5 * time.Second)

    go function2(ctxWithCancel, cancelFunction)

    time.Sleep(5 * time.Second)

    // Done signal is only received when function2 is called
    <-ctxWithCancel.Done()
    fmt.Println("Done")
}

那么,传递这个取消函数真的是个问题吗?是否有任何与使用上下文包及其取消功能相关的最佳实践?

在您的具体示例中,代码量足够小,理解它的工作原理可能没有问题。当您用更复杂的东西替换 function1function2 时,问题就开始了。您 link 阅读的文章给出了为什么传递取消上下文可以做一些难以推理的事情的具体原因,但更一般的原则是您应该尝试将协调工作(取消、启动 goroutines)与尽可能多地完成基础工作(无论 function1function2 正在做什么)。这只会有助于更轻松地独立推理代码的子部分,并有助于简化测试。 “function2 does ”比“function2 does and also coordinates with function1”更容易理解。

无需将取消函数传递给 function2,您只需在生成的 goroutune 中调用它即可 运行 function2:

func main() {
  //...
  go func() {
    function2(ctxWithCancel)
    cancelFunction()
  }()
  //...
}

这是侄女,因为确定何时取消的协调工作全部包含在调用函数中,而不是拆分到多个函数中。


如果你想让 function2 有条件地取消上下文,请明确 return 某种值指示是否发生了某些可取消的条件:

func function2(ctx context.Context) bool {
  //...
  if workShouldBecanceled() {
    return true
  }
  //...
  return false
}

func main() {
  //...
  go func() {
    if function2(ctxWithCancel) {
      cancelFunction()
    }
  }()
  //...
}

这里我使用了一个布尔值,但通常这种模式与 errors 一起使用 - 如果 function2 returns 是非 nil error,则取消其余的作品。

根据您的工作,errgroup.WithContext 之类的内容可能对您有用。这可以协调多个并发操作,所有这些操作都可能失败,并在第一个操作失败后立即取消其他操作。


我尝试遵循的另一个关于上下文取消的最佳实践:始终确保取消函数在某个时刻被调用。从 docs 开始,调用取消函数两次是安全的,所以我经常这样做:

func main() {
  ctx, cancel := context.WithCancel(context.Background())
  defer cancel()
  //...
  if shouldCancel() {
    cancel()
  }
  //...
}

编辑回复评论:

如果您有多个长时间 运行ning 操作(例如,服务器、连接等)并且您希望在第一个停止时立即关闭所有操作,上下文取消是一种合理的方法。但是,我仍然建议您在单个函数中处理所有上下文交互。像这样的东西会起作用:

func operation1(ctx context.Context) {
   for {
     select {
     case <-ctx.Done():
       return
     default:
     }
     //...
   }
}

func operation2(ctx context.Context) {
  // Similar code to operatoin1()
}

func main() {
  ctx, cancel := context.WithCancel(context.Background())
  var wg sync.WaitGroup
  wg.Add(2)
  go func() {
    defer wg.Done()
    defer cancel()
    operation1(ctx)
  }()
  go func() {
    defer wg.Done()
    defer cancel()
    operation2(ctx)
  }()
  wg.Wait()
}

其中一个操作终止后,另一个操作将被取消,但 main 仍在等待两个操作完成。这两个操作根本不需要担心管理这个问题。