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
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!
LikeLike