//注释掉的地方时另一种锁的应用
#include <windows.h>
#include <iostream.h>
int i = 0;
HANDLE hMutex;
DWORD WINAPI threadproc1(LPVOID lpParameter);
DWORD WINAPI threadproc2(LPVOID lpParameter);
CRITICAL_SECTION Semo;
int main(int argc, char* argv[])
{
HANDLE hthread1, hthread2;
hMutex = CreateMutex(NULL, FALSE, "ru");
if(GetLastError() == ERROR_ALREADY_EXISTS)
{
cout<<"已经有一个实例开启!"<<endl;
return 0;
}
//InitializeCriticalSection(&Semo);
hthread1 = CreateThread(NULL, 0,threadproc1, NULL, 0, NULL);
hthread2 = CreateThread(NULL, 0,threadproc2, NULL, 0, NULL);
while(1)
{
WaitForSingleObject(hMutex,INFINITE);
//::EnterCriticalSection(&Semo);
if(i < 100)
{
cout<<"thread3"<<" "<<i<<endl;
i++;
}
ReleaseMutex(hMutex);
// ::LeaveCriticalSection(&Semo);
if(i == 100) break;
}
CloseHandle(hthread1);
CloseHandle(hthread2);
Sleep(5000);
return 0;
}
DWORD WINAPI threadproc1(LPVOID lpParameter)
{
while(1)
{
WaitForSingleObject(hMutex,INFINITE);
//::EnterCriticalSection(&Semo);
if(i < 100)
{
cout<<"thread1"<<" "<<i<<endl;
i++;
}
if(i == 100) break;
ReleaseMutex(hMutex);
//::LeaveCriticalSection(&Semo);
}
return 0;
}
DWORD WINAPI threadproc2(LPVOID lpParameter)
{
while(1)
{
WaitForSingleObject(hMutex,INFINITE);
//::EnterCriticalSection(&Semo);
if(i < 100)
{
cout<<"thread2"<<" "<<i<<endl;
i++;
}
ReleaseMutex(hMutex);
//::LeaveCriticalSection(&Semo);
}
return 0;
}