#include <iostream> #include <Windows.h>
using namespace std;
volatile LONG lfsSpinLock = 0; int num = 0; // lfsSpinLock is a 'long' and when it is '1' it is locked, and '0' is unlocked #define ENTER_LFS_LOCK_ while( InterlockedExchange( &lfsSpinLock, 1 ) == 1 ){ Sleep( 10 ); } #define EXIT_LFS_LOCK_ InterlockedExchange( &lfsSpinLock, 0 );
void Func1() {
//Wait to access the resource. 等待资源
ENTER_LFS_LOCK_;
for (int i = 0;i < 20; i++) { num++; cout<<num<<endl; }
EXIT_LFS_LOCK_;
}
int _tmain(int argc, _TCHAR* argv[]) { HANDLE hThrd[4];
DWORD dwThrdID[4]; hThrd[0] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)Func1, NULL, 0, &dwThrdID[0]); hThrd[1] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)Func1, NULL, 0, &dwThrdID[1]); hThrd[2] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)Func1, NULL, 0, &dwThrdID[2]); hThrd[3] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)Func1, NULL, 0, &dwThrdID[3]);
WaitForMultipleObjects(4, hThrd, TRUE, INFINITE); for (int i=0;i<4;i++) { CloseHandle(hThrd[i]); }
system("pause"); return 0; }
|