@ Enigmatism is gaining prestige here (if not the point, unfortunately), referring to this blog about missed locks , which, in turn, links the links to this blog about optimizing processor reordering , which is the real meat of the answer.
In general, CPUs can (and do) apply optimization to code, which includes changing the order in which read / write operations are performed. These changes ensure that they are consistent and invisible in the thread in which they are executed. However, they cannot (cannot) guarantee consistency between multiple threads accessing shared memory. A lock, as shown in the example in the initial question, imposes restrictions on access to this shared memory, which restore consistency.
As I said, this is a summary. I canβt add anything to the description on the blogs related to the above, so put off anyone interested in the full answer to follow these links.
@Enigmativity, I will still accept this as a response from you if you post it as such. Otherwise, I will accept this answer and close it.
source share