I've got a common problem (that was posted here in several variations) of a process running multiple threads that each may read or write to a group of common variables (for the simplicity - say it's single variable).
Each variable should be protected against parallel write, and allow parallel read.
I've seen several solutions, and decided to focus on the following one that is using guards (mentioned in this link)
However, I Couldn't figure out the following principles:
MutexGuard class : shouldn't it be implemented as singleton. otherwise, each thread will create new mutex, other than waiting on a single common mutex.
if the class MutexGuard is not singleTon, so at least the m_Mutex should be static so it will be shared among all instances of this class.
why are function1 and function2 defined as static. this way it can be called without the context of an instance (class is just namespace), and the value of m_SharedVar might be missing.
is there any easy way to modify the implementation for multi-readers / single writer lock ? should i only change the mutex type in this case ?
class MutexGuard { MutexType & m_Mutex; public: inline MutexGuard(MutexType & mutex) : m_Mutex(mutex) { m_Mutex.lock(); }; inline ~MutexGuard() { m_Mutex.unlock(); }; } class TestClass { MutexType m_Mutex; double m_SharedVar; public: TestClass() : m_SharedVar(4.0) { } static void Function1() { MutexGuard scopedLock(m_Mutex); //lock the mutex m_SharedVar+= 2345; //mutex automatically unlocked } static void Function2() { MutexGuard scopedLock(m_Mutex); //lock the mutex m_SharedVar*= 234; throw std::runtime_error("Mutex automatically unlocked"); } }