Software & Finance





Visual C++ - Multithreading Synchronization - Mutex - CMutex, CSingleLock, WaitForSingleObject





Multithreading are very interesting part of programming languages. Visual C++ offers many ways to support  multithreading. You can create thread easily using _beginthread function.

 

Mutex objects are used to synchronize between multiple processes rather than multithread. Named mutexes can be created and accessed between two applications (client/server or peer to peer).

 

In this example, I have written one application using mutex. It will check whether any other instances of the same application is running or not. If another instance is running, then it will display the message "another instance of the same application is running" and then it will exit.

 

Note that if you are using mutex between multiple threads and mutex object is defined globally, the thread which is locking should be responsible for unlocking the mutex object. If you try unlock the mutex object with another thread, it would fail with the GetLastError return code - 288 ERROR_NOT_OWNER - Attempt to release mutex not owned by caller.

 


Source Code


 

#include <afx.h>

#include <afxwin.h>

#include <afxext.h>

#include <atlbase.h>

#include <atlstr.h>

 

#include <afxmt.h>

#include <conio.h>

 

#include <iostream>

#include <vector>

#include <process.h>

 

CMutex my_mutex(FALSE, _T("MyAppMutex"));

CSingleLock mutex_lock(&my_mutex, FALSE);

 

CWinApp theApp;

 

using namespace std;

 

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])

{

       int nRetCode = 0;

 

       // initialize MFC and print and error on failure

       if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))

       {

              // TODO: change error code to suit your needs

              _tprintf(_T("Fatal Error: MFC initialization failed\n"));

              nRetCode = 1;

       }

       else

       {

        if(mutex_lock.IsLocked() == FALSE)

        {

            BOOL bRet = mutex_lock.Lock(100);

            if(bRet == TRUE)

            {

                std::cout << "Captured the lock, press a key to exit\n";

                char ch = getch();

            }

            else

            {

                std::cout << "Another instance of the same application is running.\n";

                return 0;

            }

        }

       } 

       return nRetCode;

}

 

Click here to download the VS2005 project and executable

 

Output


 

First Time

Captured the lock, press a key to exit

 

Second Time with out exiting the first time running application

Another instance of the same application is running.