Go closure captured variable and shared data?

huangapple go评论79阅读模式
英文:

Go closure captured variable and shared data?

问题

我刚刚观察并确认,Go闭包通过引用捕获外部变量。如果变量被捕获到一个Goroutine中,并且该Goroutine被多个线程复用,

  • 在闭包中修改该值是否安全?
  • 如果不安全,为什么Go不阻止这种情况发生?
  • 或者它是否采用了某种安全机制?(比如锁)
英文:

I just observed and confirmed that Go closure captures external variables by reference. If the variable is captured into a Goroutine and if the Goroutine multiplexed into different thread,

  • is it safe to modify the value in the closure?
  • If it's not safe, why doesn't Go prevent this?
  • Or does it employ some safety mechanism? (such as lock)

答案1

得分: 10

Go在闭包中确实通过引用捕获外部变量,正如你所注意到的。

在闭包中修改这个值是安全的吗?

它就像任何其他变量一样,所以与在普通的Go代码中一样适用相同的规则。修改它是安全的,但如果你在并发修改它,那么你需要提供自己的锁定机制或使用原子类型。

详细信息请参阅Go内存模型

如果不安全,为什么Go不阻止这种情况发生?

这与访问任何其他在go例程之间共享的变量没有区别。你可以安全地进行访问,也可以不安全地进行访问——Go允许你自由地自毁。

Go有一个出色的竞争检测器,可以找出并发变量访问问题。

或者它是否使用了一些安全机制?(比如锁)

不,Go从不为你锁定东西——你需要使用sync包中提供的原语,或者遵循Go的哲学——不要通过共享内存来通信,而是通过通信来共享内存,也就是使用通道在go例程之间进行通信。

英文:

Go does capture external variables by reference in closures as you've noticed.

Is it safe to modify the value in the closure?

It is a variable just like any other so the same rules apply as would in normal Go code. It is safe to modify it, but if you are modifying it concurrently then you need to supply your own locking or use an atomic type.

See The Go Memory model for the full details.

If it's not safe, why don't Go prevent this?

It is no different from accessing any other variable shared between go routines. You can do it safely and you can do it unsafely - Go gives you the freedom to shoot yourself in the foot if you want!

Go has an excellent race detector though which can find concurrent variable access problems.

Or does it employ some safety machinery? (such as lock)

No. Go never locks stuff for you - you need to use the primitives provided in the sync package or follow the Go philosophy of Do not communicate by sharing memory; instead, share memory by communicating, ie use channels to speak between go routines.

huangapple
  • 本文由 发表于 2013年11月9日 14:55:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/19873321.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定