要实现这样的功能,方法灰常多,利用命名的事件对象,命名的互斥对象都可以实现,下面写出这两种方法的实现:
1.命名的互斥对象:
void main()
{
HANDLE hThread1 ;
HANDLE hThread2 ;
// 创建互斥对象
hMutex = CreateMutex(NULL, TRUE, "tickets") ;
if(hMutex)
{
if(ERROR_ALREADY_EXISTS == GetLastError())
{
cout << "only one instance can run!" << endl ;
return ;
}
}
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) ;
Sleep(4000) ;
}
2.命名的事件对象
g_hEvent = CreateEvent(NULL, FALSE, FALSE, "tickets") ;
if (g_hEvent)
{
if (ERROR_ALREADY_EXISTS == GetLastError())
{
cout << "only ont instance can run!" << endl ;
return ;
}
}