In Golang what ensures calls to Mutex methods are not reordered relative to other statements?

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

In Golang what ensures calls to Mutex methods are not reordered relative to other statements?

问题

根据我阅读的《Go内存模型》文章,编译器允许重新排序语句,尽管这种能力受到一定限制。

然而,我不明白什么限制了包含Mutex锁定和解锁的语句的重新排序,例如:

mu.RLock()
d := primes[i]
mu.RUnlock()

是什么保证第二行不会被重新排序到最前面?这是否与以下短语有关:

不引入数据竞争也意味着不假设调用的函数总是返回或不包含同步操作。

也就是说,仅仅依赖于Lock()是一个函数调用(我假设,并且没有以某种方式内联)- 或者存在其他不同的机制/逻辑?

英文:

As I understand upon reading Go Memory Model article, compiler is allowed to reorder statements, though such ability is subject to certain restrictions.

However I can't understand what restricts reordering of statements which include Mutex locking and unlocking, i.e.:

mu.RLock()
d := primes[i]
mu.RUnlock()

What ensures the second line is not reordered to the top? Is it about the phrase:

Not introducing data races also means not assuming that called functions always return or are free of synchronization operations.

i.e. simply relying on fact that Lock() is a function call (and I suppose, not inlined somehow) - or there is something different mechanism/logic?

答案1

得分: 2

一个代码块中的语句按照源代码的顺序执行(忽略包块的特殊情况,其中依赖项控制顺序)。优化必须保留这种执行顺序的副作用。

规范没有明确说明代码块中的语句按照源代码的顺序执行。也许作者认为这是如此明显,不需要特别说明。

如果编译器无法证明iprimesprimes的后备只对当前goroutine可见,那么编译器不能重新排序语句,否则会改变语句的副作用。

英文:

Statements in a block are executed in source code order (ignoring the special case of the package block where dependencies control order). Optimizations must retain the side effects of this execution order.

The specification does not specifically state that statements in a block are executed in source code order. Perhaps the authors thought it was so obvious that it does not need to be said.

If the compiler cannot prove that i, primes or the backing of primes is only visible to the current goroutine, then compiler cannot reorder the statements without changing the side effects of the statements.

huangapple
  • 本文由 发表于 2023年7月8日 15:27:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76641824.html
匿名

发表评论

匿名网友

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

确定