将context.Context传递给在单独的goroutine中执行的闭包的最佳方法 [英] Best way to pass context.Context to a closure executed in a separate goroutine

查看:25
本文介绍了将context.Context传递给在单独的goroutine中执行的闭包的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

context.Context 传递给闭包以在单独的goroutine中执行的最佳方法是什么?

What is best way to pass context.Context to closure to be executed in a separate goroutine?

由于我没有在闭包内对 context.Context 进行突变,因此我认为这两个选项均有效.第二个选项可以通过不复制界面来节省一点内存.

Since I'm not mutating context.Context inside the closure, I assume both options are valid. 2nd option can save me tiny bit of memory by not copying the interface.

1)作为参数传递

func run(ctx context.Context) {
  for i := 0; i <= 5; i++ {
    go func(id int, ictx context.Context) {
      for {
        select {
          case <- ictx.Done():
            return
          default:
            // do something
        }
      }
    }(i, ctx)
  }
}

2)公开外部上下文变量

2) expose outer context variable

func run(ctx context.Context) {
  for i := 0; i <= 5; i++ {
    go func(id int) {
      for {
        select {
          case <- ctx.Done():
            return
          default:
            // do something
        }
      }
    }(i)
  }
}

推荐答案

两者都可以.要记住的关键是上下文是不可变的.这意味着没有争用条件的风险,在您尝试读取上下文时,其他一些goroutine正在更新上下文,因此您无需担心正常的同步方法.

Both should be fine. The key to remember is that contexts are immutable. This means there's no risk of a race condition where some other goroutine is updating the context as you're trying to read it, so you don't need to worry about the normal synchronization methods.

因此,简而言之,不需要任何特殊操作,因此#2很好.由于#1实际上并没有执行闭包,因此在要执行带有上下文参数的命名函数的情况下,它是理想的选择.

So in short, nothing special is needed so #2 is just fine. Since #1 isn't actually executing a closure, it's ideal in situations where you want to execute a named function, which takes a context argument

有关术语的说明:您最初的问题(为清晰起见,我对其进行了编辑)询问有关执行闭包中的goroutine"的问题.从技术上来讲,这是胡说八道.但这是一个普遍的困惑.Goroutines是轻量级的执行线程.函数是代码的一部分.它们不是一回事,因此将函数或闭包称为goroutines并没有任何意义.有关更多详细信息,请参见此答案.

Note on terminology: Your original question (which I edited for clarity) asked about executing "a goroutine in a closure." Technically speaking, this is non-sense. But it's a common confusion. Goroutines are light-weight threads of execution. Functions are bits of code. They are not the same thing, so referring to functions or closures as goroutines doesn't really make sense. See this answer for more details.

这篇关于将context.Context传递给在单独的goroutine中执行的闭包的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆