猿问

带上下文取消的异步/等待模式

在我的应用程序中,我需要具有上下文取消支持的异步/等待模式。在实践中,我有一个类似的功能:


func longRunningTask() <-chan int32 {

    r := make(chan int32)


    go func() {

        defer close(r)

        

        // Simulate a workload.

        time.Sleep(time.Second * 3)

        r <- rand.Int31n(100)

    }()


    return r

}

但是,它不支持上下文取消。为了解决这个问题,我可以添加一个参数并修改函数以ctx.Done()在 select 语句中等待通道信号,如果上下文被取消则中止操作。


如果这样做,如果运行两次或更多次,函数将不会正确中止(因为上下文指针将被共享),因为上下文取消通道只接收一个信号:


ctx := ...

go func() { r := <-longRunningTask(ctx) } // Done() works

go func() { r := <-longRunningTask(ctx) } // ?

// cancel() ...

这是我看到的关于完成的内容:


   // go/context.go


   357  func (c *cancelCtx) Done() <-chan struct{} {

   358      c.mu.Lock()

   359      if c.done == nil {

   360          c.done = make(chan struct{})

   361      }

   362      d := c.done

   363      c.mu.Unlock()

   364      return d

   365  } // Done() returns the same channel for all callers, and cancellation signal is sent once only

go 源是否context真的不支持中止调用其他“长时间运行”函数的函数,“链式取消”?


有哪些选项可以编写支持在无限递归.Done()使用中取消上下文的异步函数?


qq_笑_17
浏览 180回答 1
1回答

有只小跳蛙

go 源是否意味着上下文并不真正支持调用其他“长时间运行”函数的函数的中止,“链式取消”?不可以。任务可以调用其他长时间运行的任务,将上下文传递到调用链中。这是一种标准做法。如果上下文被取消,嵌套调用将出错并沿着调用堆栈冒泡取消错误有哪些选项可以编写异步函数,以支持在 .Done() 使用的无限递归中取消上下文?递归与几个采用上下文的嵌套调用没有什么不同。如果递归调用采用上下文输入参数并返回错误(即检查),则递归调用链将像一组非递归嵌套调用一样冒泡取消事件。首先,让我们更新您的包装函数以支持context.Context:func longRunningTask(ctx context.Context) <-chan int32 {&nbsp; &nbsp; r := make(chan int32)&nbsp; &nbsp; go func() {&nbsp; &nbsp; &nbsp; &nbsp; defer close(r)&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; // workload&nbsp; &nbsp; &nbsp; &nbsp; i, err := someWork(ctx)&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; r <- i&nbsp; &nbsp; }()&nbsp; &nbsp; return r}然后someWork- 使用睡眠工作负载将如下所示:func someWork(ctx context.Context) (int32, error) {&nbsp; &nbsp; tC := time.After(3*time.Second) // fake workload&nbsp; &nbsp; // we can check this "workload" *AND* the context at the same time&nbsp; &nbsp; select {&nbsp; &nbsp; case <-tC:&nbsp; &nbsp; &nbsp; &nbsp; return rand.Int31n(100), nil&nbsp; &nbsp; case <-ctx.Done():&nbsp; &nbsp; &nbsp; &nbsp; return 0, ctx.Err()&nbsp; &nbsp; }}这里要注意的重要一点是,我们可以改变虚假的“工作负载”(time.Sleep),使其成为一个通道——从而通过select语句观察它和我们的上下文。大多数工作负载当然不是那么简单……幸运的是,Go 标准库完全支持context.Context. 因此,如果您的工作负载包含大量可能长时间运行的 SQL 查询,则可以为每个查询传递一个上下文。与 HTTP 请求或 gRPC 调用相同。如果您的工作负载包含这些调用中的任何一个,则传入父上下文将导致任何这些潜在的阻塞调用在上下文被取消时返回错误 - 因此您的工作负载将返回取消错误,让调用者知道什么发生了。如果您的工作负载不适合此模型,例如计算大型 Mandelbrot-Set 图像。在每个像素后检查取消上下文可能会对性能产生负面影响,因为轮询选择不是免费的:select {case <-ctx.Done(): // polling select when `default` is included&nbsp; &nbsp; return ctx.Err()default:}在这种情况下,可以应用调整,如果说像素以 10,000/s 的速率计算 - 每 10,000 个像素轮询上下文将确保任务将在取消点后不迟于 1 秒内返回。
随时随地看视频慕课网APP

相关分类

Go
我要回答