Welcome to Blogs @ Andrew Qu
Blog Index
All blogs
Search results

VC++ How to Allow Only One Copy of a Program to Run Using Mutex


On occasions, we want only one copy of a program to run at a time. Here we show one of the ways to solve the problem using mutex.

Mutex Basics

Mutex is a way of multi-threading. It is particularly designed to mutually exclude each other. For example, if two parts of a program should not be executed at the same time, that is, if one part is running, the other part should not run, then we can use mutex to achieve this.

The way to do this is that we create a shared mutex object. Whenever one part of the program is to run, we check if the object is locked. If it is not locked, then we lock the object and execute the code. After the execution, we unlock the object. If the object is locked, then we wait until it is unlocked.

In Visual C++, a mutext object can be global or local. A local object is shared by parts of the same program instance. A global object is shared across program instances or even programs. That is 2 running copies of a same program can share a global mutext object. Also 2 different programs can also share a global mutex object.

To solve our problem, we need the global mutex object.

The code is very simple as shown below
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
    if( OpenMutex(MUTEX_ALL_ACCESS, FALSE, _T("Global\\TestProgramName")) != NULL)
        AfxMessageBox(_T("Another copy of the program is running. Click [OK] to exit."));
        return 1;

    CreateMutex(NULL, FALSE, _T("Global\\TestProgramName"));

// Other codes ...

    return 0;

*** END ***
Ads from Google
Dr Li Anchor Profi
Engineering anchorage plate design system
©Andrew Qu, 2015. All rights reserved. Code snippets may be used "AS IS" without any kind of warranty. DIY tips may be followed at your own risk.