Concurrency three features (thread safety three features)

Why are these three characteristics proposed? That is, if a certain piece of code does not satisfy atomicity/visibility/ordering, then concurrency safety issues may arise.

Atomicity (my understanding): For code segments, only one thread is allowed to execute at a time.
Visibility: After a variable is modified, it is immediately visible to other threads. Orderliness
: Code is not allowed to be reordered

Examples of violations of atomicity:

First of all, we guarantee visibility and order

i++;

Multiple threads perform the above operations at the same time

Examples of Visibility Violations:
if(i<0){
    
    
   i++;
}

First of all, we verify the order and atomicity of this piece of code, that is, only one thread is allowed to execute at a time.
Initially, i=-1, thread A executes the code block, and the result i becomes 0, and then thread B executes the code block. At the time of judgment, thread A does not see the update of variable i, enter the if logic, and read it again i, I saw the update of thread A to i, and i became 1 after B was executed. It is best if i becomes 1 and there is a problem.

Examples of violations of order

With atomicity and visibility, it seems sufficient to ensure code thread safety. Imagine that we are the designers of jvm. If we provide tools to solve the problem of code rearrangement, the code blocks that are guaranteed atomically will have problems. For example, code block A is guaranteed by atomicity, but the code in code block A may be reordered with external code, and the result is that it jumps out of the original code block, and the original code block no longer satisfies atomicity.

Guess you like

Origin blog.csdn.net/qq_41634872/article/details/110351380