#include "stdafx.h"
#include <iostream>
#include <Windows.h>
using namespace std;
DWORD WINAPI Fun1Proc(LPVOID lpParameter);
DWORD WINAPI Fun2Proc(LPVOID lpParameter);HANDLE hMutex;int main()
{
HANDLE hThread1;
HANDLE hThread2; hThread1=CreateThread(NULL,0,Fun1Proc,NULL,0,NULL);
hThread2=CreateThread(NULL,0,Fun2Proc,NULL,0,NULL);
CloseHandle(hThread1);
CloseHandle(hThread2); hMutex = CreateMutex(NULL,TRUE,LPCTSTR("tickets"));
if(hMutex)
{
if(ERROR_ALREADY_EXISTS == GetLastError())
{
cout<<"only one instance can run"<<endl;
Sleep(1000);
exit(0);
}
}
WaitForSingleObject(hMutex,INFINITE);
ReleaseMutex(hMutex);
ReleaseMutex(hMutex);
Sleep(10000);
// return 0;
}DWORD WINAPI Fun1Proc(LPVOID lpParameter)
{
WaitForSingleObject(hMutex,INFINITE);
cout<<"thread 1 is running"<<endl;
return 0;
}DWORD WINAPI Fun2Proc(LPVOID lpParameter)
{
WaitForSingleObject(hMutex,INFINITE);
cout<<"thread 2 is running"<<endl;
return 0;
}
VC++深入详解第579页的例子,为什么第二次运行的结果是”thread 2 is running
thread 2 is running
only one instance can run “
这个是怎么回事,按道理说应该只显示”only one instance can run“求大神解释一下。只有一个实例运行VC++

解决方案 »

  1.   

    这个例子有问题吧,应该将下面的代码
    hThread1=CreateThread(NULL,0,Fun1Proc,NULL,0,NULL);
    hThread2=CreateThread(NULL,0,Fun2Proc,NULL,0,NULL);
    CloseHandle(hThread1);
    CloseHandle(hThread2);移到 CreateMutex(NULL,TRUE,LPCTSTR("tickets")); 之后吧。
      

  2.   


    //昨天刚弄过 在XXXApp::InitInstance()中添加下面代码  直接可以用
    HANDLE hMutexOneInstantance;
    BOOL bFound=FALSE;
    hMutexOneInstantance=CreateMutex(NULL,TRUE,_T("XXX"));
    if(GetLastError()==ERROR_ALREADY_EXISTS)
    bFound=TRUE;
    if(hMutexOneInstantance)
    ReleaseMutex(hMutexOneInstantance);
    if (bFound==TRUE)
    {
    AfxMessageBox(_T("该程序已经启动!"));
    HWND handle=FindWindow(NULL,_T("Frs"));
    if(handle)
    {   
    ::ShowWindow(handle,1);
    ::SetForegroundWindow(handle);
    ::SetActiveWindow(handle);
    }
    return false;
    }
      

  3.   


    hMutex = CreateMutex(NULL,FALSE,LPCTSTR("tickets"));
    if(hMutex == NULL || ERROR_ALREADY_EXISTS == ::GetLastError())
    {
    cout<<"only one instance can run"<<endl;
    Sleep(1000);
    exit(0);}