Understanding the principle of volatile visibility and order

This is mainly to explain the understanding of volatile to ensure the orderliness of instructions

The bottom layer of order is achieved through read barriers and write barriers (this is also the realization principle of visibility). The
read barrier guarantees that when a volatile modified variable is read, there are other shared variable read codes behind it. Read from main memory, not from thread cache. For
example:

public void actor1(I_Result r) {
    
    
    if(ready) {
    
    //读屏障
        r.r1 = num + num;
    } else {
    
    
        r.r1 = 1;
    }
}

The write barrier guarantees that when the volatile modified variable is assigned, when there is other shared variable assigned code before it, it will be written to the main memory, not to the thread cache. For
example:

public void actor2(I_Result r) {
    
    
    num = 2;
    ready = true;//写屏障
}

The summary is:
the code after reading will not appear before the volatile variable
The code before writing will not appear after the volatile variable

Note: From the
above, we can infer that
the code before reading may appear after reading
. The code after writing may appear before writing.
This I have verified with the code and it does exist.
Therefore, volatile cannot prevent instruction interleaving
. Orderliness, it cannot control the ordering of instructions between multiple threads

Guess you like

Origin blog.csdn.net/Brave_heart4pzj/article/details/113832944