#include "stdafx.h"
#include "windows.h"
#include "iostream"
#include "process.h"
long number = 0;
unsigned int _stdcall ThreadFunc(void* param)
{
InterlockedExchangeAdd(&number, 1);
//number ++;
return 0;
}
unsigned int _stdcall ThreadFunc2(void *param)
{
InterlockedExchangeAdd(&number,3);
//number ++;
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE hThread1 = (HANDLE)_beginthreadex(NULL,0,ThreadFunc,0,0,0);
HANDLE hThread2 = (HANDLE)_beginthreadex(NULL,0,ThreadFunc2,0,0,0);
WaitForSingleObject(hThread1, INFINITE);
WaitForSingleObject(hThread2, INFINITE);
printf("%d",number);
return 0;
}
注:如果直接++的话,因为在++和移入寄存器的中间,有可能被令一个线程中断,从而导致变量的结果不争确。利用互锁函数,可以避免这种情况的发生。