"side-effects" of code 到底是什么意思?

What exactly is meant by "side-effects" of code?

以下引自this tutorial

我无法理解该段落的最后一行(我已将其应用为粗体)。 代码的副作用是什么意思?

Atomic actions cannot be interleaved, so they can be used without fear of thread interference. However, this does not eliminate all need to synchronize atomic actions, because memory consistency errors are still possible. Using volatile variables reduces the risk of memory consistency errors, because any write to a volatile variable establishes a happens-before relationship with subsequent reads of that same variable. This means that changes to a volatile variable are always visible to other threads. What's more, it also means that when a thread reads a volatile variable, it sees not just the latest change to the volatile, but also the side effects of the code that led up the change.

副作用只是指某种状态的修改——例如:

  • 更改变量的值;
  • 正在将一些数据写入磁盘;
  • 在用户界面中启用或禁用按钮。

所以在最后一行中,线程会看到由代码的副作用引起的任何状态变化,而不仅仅是读取的 volatile 变量。

"Side-effect" 这里的意思是线程更新了自己栈外的一些内存位置。基本上这意味着它改变了堆上某个对象的状态。

确保 volatile 字段被正确发布的同步机制也会导致(作为副作用,hihi)对任何内存写入的保证与另一个线程在更新该字段之前所做的相同.