Atomicity and visibility

Source: Internet
Author: User

First, the definition

1. Visibility

In multi-core processors, if multiple threads operate on a variable (assuming), but the multiple threads are likely to be assigned to multiple processors, the compiler optimizes the code, and when the thread processes the variable, multiple processors copy the variable from main memory to their own on-chip memory, Wait until the operation is finished, and then assign the value back to main memory. (The advantage of this is that it increases the speed of the operation because multiple processors reduce the number of times they communicate with main memory during processing), and in a single-core processor This is also the case because of a "backup" Problem!

One of the problems with this optimization is variable visibility-if thread t1 and thread T2 are arranged on separate processors, then T1 and T2 are not visible to each other when modifying variable a, and if T1 assigns a value to a and then T2 assigns a new value, T2 operation overwrites the T1 operation. This can produce unpredictable results. So, even if some operations are atomic, but if they are not visible, the presence of backups in multiple processors can make atomicity meaningless.

2. Atomicity:

As is known to all, the atom is the basic unit of matter (of course, electron, etc.), so the meaning of the atom represents-"non-divided";

By non-fractal, atomicity is the denial of multi-threaded operations (only decomposed into multi-step operations, multiple threads can operate on them: like a box with multiple ping-pong balls, many people can get the table tennis from the box; if the box has only one pingpong ball and one person takes it, the others will not get it; this is atomicity, Table tennis is atomic, and people are the equivalent of atoms.

In a nutshell-operations that are not interrupted by the thread scheduler, such as:

Assignment or return. such as "a = 1;" and "return A;" Such operations are atomic in nature.

Atomicity, whether multi-core or single-core, has atomic quantities, and only one thread can operate on it at the same time!

3. Non-atomic operation

Operations such as "A + = B" are not atomic, and in some JVMs "a + = B" may take three steps:

(1) Remove A and B

(2) Calculation a+b

(3) Write calculation results to memory

If there are two threads t1,t2 are doing such an operation. T1 after the second step has not yet had time to write the data back into memory by the thread scheduler interrupted, so T2 began to execute, T2 after the completion of the T1 and did not complete the third step done. There was a mistake at this time, and the equivalent of T2 's calculation was ignored. So the above buy iodine tablets example before synchronizing the Add method, the actual result is always less than the expected result, because many operations are ignored.

Similarly, operations such as "a++" are not atomic. So in the multi-threaded environment must remember to do synchronous operation

4. The relationship between atomicity and visibility

There is no direct correlation between atomicity and visibility. Here, we have to discuss the problems and the nature of multithreading.

(1) First, a bit of nonsense, there may be multi-core and single-core processor different distinction, here I confused, in fact, at the code level they are the same!

The multithreading of a single-core machine is actually allocating a time fragment for each thread, so in fact these threads are actually only one in the micro-period of time in the execution. The problem here is that if a thread operates a memory space and then suddenly terminates (hangs) by the thread scheduler, the CPU time is taken by another thread to operate on that space, which creates unpredictable problems.

The rationale for multicore machines is the same as this, and the difference is that at the same time multiple threads may be operating simultaneously (because each core can run an operation). As mentioned earlier, multi-core machines have problems with the visibility of multiple threads for the same memory operation because of multicore. (Visibility is also present in both single-and multi-core)

(2) Problems caused by visibility in multiple threads:

Multiple threads are not visible to each other for the same variable, causing some operations to be overwritten, such as:

count++; T1 and T2 Two threads are ready to operate it, and when T1 modifies the count value within its own storage space, it does not change the count back in time, but instead performs the count of other operations-at which point the T2 begins to perform the operation. However, it did not find that the count value was changed, resulting in a related error that the count value was not updated in time.

(3) Other questions:

The same is the count++ statement, the statement that produces the problem may also be caused by other reasons: T1 and T2 execute the statement, T1 is only a little slower than T2, T2 modified count,t1 and write their results to count, so T1 results will overwrite the results of T2, This overlay can result in an error that is not made.

(1.2) Non-atomicity caused by the problem, multiple threads in the execution of the action of one side of the "Action" "overwrite" the other party;

(5) Discussion:

Visibility issues are part of the problem of multithreading, and determining the visibility of variables can only solve a subset of multithreading problems, whereas operational atomicity is the total way to solve multithreading, because it rejects multiple threads operating the same memory at the same time.

5.volatile and Synchronized Keywords

(1) volatile

Volatile gives the variable visibility--prevents the compiler from optimizing member variables, and it modifies the member variable to force the value of the member variable to be reread from memory each time it is accessed by the thread, and when the member variable changes, forcing the thread to write the change value back to the shared memory. So at any moment two different threads always see the same value for a member variable, which is guaranteed visibility. Abstracts:

The Java language specification states that, for optimal speed, threads are allowed to save private copies of shared member variables, and only when a thread enters or leaves a synchronized block of code with a shared member variable
Comparison of the original values. This way, when multiple threads interact with an object at the same time, it is important to notice that the thread gets the changes to the shared member variables in a timely manner. And the volatile keyword is a hint.
VM: You cannot save its private copy for this member variable, but you should interact directly with the shared member variable.
Usage Recommendation: Use volatile on member variables accessed by two or more threads. You do not have to use the variable you want to access when it is already in a synchronized code block, or is a constant.
It is inefficient to use volatile to mask the necessary code optimizations in the VM, so use this keyword when necessary. Just like in C. Prohibit the compiler from doing
Optimization ~ ~ ~

Attention:

If you add the volatile modifier to a variable, it is equivalent to: once this value changes in each thread, it is flushed back to main memory, so that each thread takes out the same value. The compiler does not optimize the read and write operations of this variable. It is noteworthy, however, that volatile does not provide atomicity other than simple operations on long and double. So, even if you modify a variable to be volatile, but the operation of this variable is not atomic, in the concurrency environment, still can not avoid the occurrence of errors!

Reference Link: http://www.cnblogs.com/aigongsi/archive/2012/04/01/2429166.html

(2) Synchronized

Synchronized locks an operation or memory, and it is mutually exclusive. When a thread wants to manipulate memory or operations that are synchronized decorated, it must first acquire a lock for subsequent operations, but only one thread at a time can get the same lock (object monitor), so it only allows one thread to operate.

A simple way to understand:

Synchronized (object) method ();

This is quite a lock for Menthod (), which is the object, and when the thread wants to access the method, it needs to get the key: object's monitor for objects, if the key is not taken (before the method or operation is completed), The current thread takes away the key (Gets the object monitor) and operates the method, and when the method is finished, put the key back in place!

If the "key" is not in place, then the thread needs to wait for someone else to put the key back (waiting to go into the blocking state); If multiple threads want to get the key, they need to "compete" (typically competing based on the priority of the thread)

Atomicity and visibility

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.