Software & Finance





Visual C++ - Multithreading Synchronization - Semaphore - CSemaphore, 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.

 

Semaphore objects are used to control the number of instances running and synchronize between multiple processes rather than multithread. It behaves as if Mutex but the maximum number of instances can be set while creating semaphore.

 

In this example, I have written one application using Semaphore. It will allow running of the same application to the maximum of 3 times. After that if you try to run the same application, then it will display the message " You have reached running the maximum number of instances of this application." and then it will exit.

 


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>

 

CSemaphore ms1(3, 3, _T("MyAppSemaphore"));

CSingleLock s1(&ms1, 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(s1.IsLocked() == FALSE)

        {

            BOOL bRet = s1.Lock(100);

            if(bRet == TRUE)

            {

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

                getch();

            }

            else

            {

                std::cout << "You have reached running the maximum number of instances of this application.\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

Captured the lock, press a key to exit

 

Third Time

Captured the lock, press a key to exit

 

Fourth Time With out exiting the first 3 times of application

You have reached running the maximum number of instances of this application.