How volatile guarantees visibility and prevents reordering

1 Ensure visibility:

Memory visibility means that one CPU modifies data and is immediately visible to other CPUs.

(1) "CPU revises data":

The modification of data by the CPU always modifies the working memory first, and then synchronizes back to the main memory. It is just the modification of the volatile modified variable that will be synchronized back to the main memory immediately.

(2) "Immediately visible to other CPUs":

When CPU_A modifies the volatile variable and synchronizes back to the main memory immediately, if the variable is also cached in the working memory of CPU_B, then this variable of B will be invalidated immediately. When B wants to modify this variable, B must be from the main memory Get the value of the variable again.

 

Implementation principle:

CPU-based MESI protocol (cache coherency protocol), where M means Modify, E means Exclusive, S means Shared, and I means Invalid. If a CPU modifies the data, then the data status of this CPU will be updated to M, and the data status on other CPUs will be updated to I. This is achieved through the sniffing mechanism between CPU multi-core.

 

2 Prevent reordering:

Implementation principle:

The Memory Barrier, like a set of codes before and after the fence is divided, prevents the code without data dependency before and after the fence from reordering instructions, ensuring the order of the program to a certain extent.

 

In the singleton mode, Instance inst = new Instance(); This code is not an atomic operation, it can be divided into three steps of atomic instructions:

(1) Allocate memory address;

(2) New an Instance object;

(3) Assign the memory address to inst;

In order for the CPU to improve execution efficiency, the sequence of these three operations can be 123 or 132. If the order is 132, when the memory address is assigned to inst, there is no new singleton object on the memory address pointed to by inst. At this time, if inst is obtained, it is actually empty, and a null pointer exception will be reported. . This is why the volatile keyword is added to the singleton object in the double-checked singleton mode.

Guess you like

Origin blog.csdn.net/u012906122/article/details/103414321
Recommended