int main()
{
HANDLE hThread1;
HANDLE hThread2;
hMutex = CreateMutex(NULL, FALSE, (TEXT("tickets")));
if (hMutex)
{
if (GetLastError()==ERROR_ALREADY_EXISTS )
{
cout << "only ont instance an run!" << endl;
return 0;
}
}
hThread1 = CreateThread(NULL, 0, fun1Proc, NULL, 0, NULL);
hThread2 = CreateThread(NULL, 0, fun2Proc, NULL, 0, NULL);
CloseHandle(hThread1);
CloseHandle(hThread2);
//WaitForSingleObject(hMutex, INFINITE);
//ReleaseMutex(hMutex);
ReleaseMutex(hMutex);
ReleaseMutex(hMutex);
Sleep(4000);
return 0;
}
HANDLE hMutex;
hMutex = CreateMutex(NULL,FALSE,(TEXT("tickets")));
创建了互斥对象并且起名为tickets。若进程第二次运行,名为为tickets的互斥对象,在CreateMutex函数调用之前,就已经存在,那么该函数会返回已经存在的这个互斥对象的句柄,而这时候调用GetLastError函数将返回ERROR_ALREADY_EXISTS.所以进入if语句程序跳出