Instruction reordering problem caused by the use of the volatile keyword and solve problems

First, look at the following code:

After reordering instructions and optimized code as follows:
(! STOP) IF
the while ( to true ) {}
volatile most suitable thread is a write, read other threads occasion, if there are multiple threads concurrently write operation, still requires the use of locks or thread-safe container or atomic variables instead.

When a variable is declared volatile, it will have the following two characteristics.
· Thread Visibility: When a thread modifies modified volatile variable, regardless of whether the lock, other threads can immediately see the latest changes, while the average variable can not do this.
Prohibition instruction reordering optimization, Common variable is only dependent on result of the assignment to ensure that all places can get the correct results in the implementation of the method, but the order can not ensure consistent execution of the program code assignment of the variable.

Guess you like

Origin www.cnblogs.com/htkj/p/10932558.html