Applications must synchronize access to variables that are shared by multiple threads.
Applications must also ensure that operations on these variables are performed atomically (performed in their entirety or not at all.)
Simple reads and writes to properly-aligned 32-bit variables are atomic operations
In other words, you will not end up with only one portion of the variable updated;
all bits are updated in an atomic fashion.
However, access is not guaranteed to be synchronized.
If two threads are reading and writing from the same variable, you cannot determine if one thread will perform its read operation before the other performs its write operation.
Simple reads and writes to properly aligned 64-bit variables are atomic on 64-bit Windows.
Reads and writes to 64-bit values are not guaranteed to be atomic on 32-bit Windows.
Reads and writes to variables of other sizes are not guaranteed to be atomic on any platform.
The Interlocked API
The interlocked functions provide a simple mechanism for synchronizing access to a variable that is shared by multiple threads.
They also perform operations on variables in an atomic manner.
The threads of different processes can use these functions if the variable is in shared memory.
The InterlockedIncrement and InterlockedDecrement functions combine the steps involved in incrementing or decrementing a variable into an atomic operation.
This feature is useful in a multitasking operating system, in which the system can interrupt one thread execution to grant a slice of processor time to another thread.
Without such synchronization, two threads could read the same value, increment it by 1, and store the new value for a total increase of 1 instead of 2.
The interlocked variable-access functions protect against this kind of error.
如果不同步情况下,如果两个线程同时读取一个变量,并把该变量加1.结果将是有可能是增加1 而不是增加2. 原子锁将确保变量的访问不会发生这种错误.
Most of the interlocked functions provide full memory barriers on all Windows platforms.
There are also functions that combine the basic interlocked variable access operations with the acquire and release memory ordering semantics supported by certain processors.
Each of these functions contains the word "Acquire" or "Release" in their names;
for example, InterlockedDecrementAcquire and InterlockedDecrementRelease.
Acquire memory semantics specify that the memory operation being performed by the current thread will be visible before any other memory operations are attempted.
Release memory semantics specify that the memory operation being performed by the current thread will be visible after all other memory operations have been completed.
These semantics allow you to force memory operations to be performed in a specific order. Use acquire semantics when entering a protected region and release semantics when leaving it.
Acquire Memory Semantics 当内存正在被当前线程操作时,其他内存操作在尝试时,内存是可见性的.
Release memory semantics 当内存正在被当前线程操作时,只有当前线程内存操作完成时,内存才是可见的.