一 较老的实现函数
LONG InterlockedIncrement(PLONG plAddend);
LONG InterlockedDecrement(PLONG plAddend);
这两个函数只能对指定的数实现加1或减1,现在他们已经有其他函数代替了,先看他们使用的一个例子:
- // 11.cpp : main project file.
- #include "stdafx.h"
- #include "iostream"
- #include "windows.h"
- using namespace std;
- using namespace System;
- long g_I = 0;
- int main(array<System::String ^> ^args)
- {
- cout << g_I << endl;
- InterlockedIncrement(&g_I);
- cout << g_I << endl;
- InterlockedDecrement(&g_I);
- cout << g_I << endl;
- getchar();
- return 0;
- }
结果为:0 1 0
二 新的方法
1 LONG InterlockedExchangeAdd(
PLONG plAddend,
LONG Increment);
可以指定增加或减少多少
如 InterlockedExchangeAdd(&g_I, 2);即加2
InterlockedExchangeAdd(&g_I, -2);即减2
2
InterlockedExchange 和 InterlockedExchangePointer
先看他们定义:
- LONG
- WINAPI
- InterlockedExchange (
- __inout LONG volatile *Target,
- __in LONG Value
- );
- #define InterlockedExchangePointer(Target, Value) /
- (PVOID)InterlockedExchange((PLONG)(Target), (LONG)(Value))
第二个函数是一个宏,他们实现的功能是:能够以原子操作方式用第二个参数中传递的值来取代第一个参数中传递的当前值。
看他们的使用例子:
- #include "stdafx.h"
- #include "iostream"
- #include "windows.h"
- using namespace std;
- using namespace System;
- long g_I = 0;
- int main(array<System::String ^> ^args)
- {
- cout << g_I << endl;
- InterlockedExchangeAdd(&g_I, 2);
- cout << g_I << endl;
- InterlockedExchange(&g_I, 0);
- cout << g_I << endl;
- int i = 5;
- InterlockedExchangePointer(&g_I, i);
- cout << g_I << endl;
- getchar();
- return 0;
- }
说明:这些函数都有一个缺点,即他们的传入参数须为长整型,不能是结构,如果是修改结构等数据,须使用另外的方法,可以看我的另外一篇关于对象安全的访问