With mutexes (mutexes), a mutex is inherently multithreaded, preventing multiple threads from accessing the same resource and causing a conflict. You can create a mutex object with CreateMutex, which is essentially a kernel object.
Add the following code to the startup portion of any WIN32 program (including GDI and console) (the console program's main function, the MFC program's CWinApp derived class's InitInstance member function, the RAWSDK program's WinMain function):
hMutex=CreateMutex(
NULL,//nosecurityattributes
FALSE,//initiallynotowned
"RunOnlyOneInstance");//命名Mutex是全局对象
//在所有的process都可以访问到
if(hMutex==NULL||ERROR_ALREADY_EXISTS==::GetLastError())
{
//程序第二次或以后运行时,会得到Mutex已经创建的错误
returnFALSE;
}
Hey, is not not findwindow elegant and simple much?
In addition, what if you want to qualify a program to run N instances at the same time?
Tips: Signal Volume (semaphore).