关于7cat同学的原子结构测试实例
在windows下:以下代码能借助原子操作锁完成计数器的正常运作。(感谢7cat支持)在这里记录一下。#include "stdafx.h"
#include <Windows.h>
long nCount = 0;
extern "C"
{
LONG _InterlockedIncrement( LONG* pn );
LONG _InterlockedDecrement( LONG* pn );
};
DWORD WINAPI Add(PVOID pvParam)
{
for(int i = 0; i<1000; i++)
{
_InterlockedIncrement(&nCount);
}
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
nCount = 0;
HANDLE* hThreadID = new HANDLE;
for(int i = 0; i < 10; i++)
{
DWORD dwThreadID = 0;
HANDLE hThread = CreateThread(NULL, 0, Add, NULL, 0, &dwThreadID);
hThreadID = hThread;
}
WaitForMultipleObjects(10, hThreadID, TRUE, INFINITE);
printf_s("nCount=%d", nCount);
getchar();
return 0;
}
页:
[1]