Skip to content

In C++, how do I create and use mutex?

In a C++ implementation file I normally use:

// *.cxx

#include <mutex>

namespace {
  std::mutex g_lock;
} // anonymous namespace

void MyClass::myThreadSafeMethod()
{
  g_lock.lock();
  // do something that is not thread safe
  g_lock.unlock();
}

Sometimes it is useful to only allow one instance (process) of a program to run, to do this you can use:

bool MyClass::startSingleInstance(const std::string & mutexName)
{
#ifdef __linux__
// linux?
#else
  HANDLE hMutex = OpenMutex(MUTEX_ALL_ACCESS, 0, mutexName.c_str());
  if (hMutex)
    return false; // This mutex is already running...
  hMutex = CreateMutex(NULL, FALSE, mutexName.c_str());
  DWORD dwError = GetLastError();
  if(dwError != 0)
    throw std::runtime_error("Unknown errors detected while creating mutex: '" + mutexName + "'");
  return true;
#endif
}

Categories

C++

Tags

, , ,

TheSoftwareProgrammer View All

I like science and writing software.

One thought on “In C++, how do I create and use mutex? Leave a comment

  1. You really make it seem really easy along with your presentation however I find this matter to be really something which I think I’d never understand. It kind of feels too complicated and very broad for me. I am taking a look forward for your next put up, I will try to get the dangle of it!

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: