InterlockedIncrement

InterlockedIncrement[align=center][/align]

InterlockedIncrement函数的作用?为何要用此函数?

看一段MSDN上的说明:
InterlockedIncrement Function

Increments (increases by one) the value of the specified 32-bit variable as an atomic operation.

To operate on 64-bit values, use the InterlockedIncrement64 function.


LONG __cdecl InterlockedIncrement(
  __in_out      LONG volatile* Addend
);

Parameters
Addend
A pointer to the variable to be incremented.

Return Value
The function returns the resulting incremented value.

Remarks
The variable pointed to by the Addend parameter must be aligned on a 32-bit boundary; otherwise, this function will behave unpredictably on multiprocessor x86 systems and any non-x86 systems.

The interlocked functions provide a simple mechanism for synchronizing access to a variable that is shared by multiple threads. This function is atomic with respect to calls to other interlocked functions.

This function is implemented using a compiler intrinsic where possible. For more information, see the header file and _InterlockedIncrement.

This function generates a full memory barrier (or fence) to ensure that memory operations are completed in order.

InterlockedIncrement函数可以实现对变量的同步操作,当多个线程或进程操作同一个变量时,此函数可以保证对操作的变量同步。

举个例子:如果一个变量 Long value =0;
  首先说一下正常情况下的加减操作:value+=1;
  1:系统从Value的空间取出值,并动态生成一个空间来存储取出来的值;
  2:将取出来的值和1作加法,并且将和放回Value的空间覆盖掉原值。加法结束。
  如果此时有两个Thread ,分别记作threadA,threadB。
  1:threadA将Value从存储空间取出,为0;
  2:threadB将Value从存储空间取出,为0;
  3:threadA将取出来的值和1作加法,并且将和放回Value的空间覆盖掉原值。加法结束,Value=1。
  4:threadB将取出来的值和1作加法,并且将和放回Value的空间覆盖掉原值。加法结束,Value=1。
  最后Value =1 ,而正确应该是2;这就是问题的所在,InterLockedIncrement 能够保证在一个线程访问变量时其它线程不能访问。

你可能感兴趣的:(InterlockedIncrement)