diff --git a/LCS/Common/include/Common/Thread/Mutex.h b/LCS/Common/include/Common/Thread/Mutex.h index 9f2dd8f1d8ff0f9d29367d5831ad8cbeddc671aa..b29e915db842d1f3ee1c8b3275d2295d9aa1266d 100644 --- a/LCS/Common/include/Common/Thread/Mutex.h +++ b/LCS/Common/include/Common/Thread/Mutex.h @@ -70,7 +70,11 @@ class Mutex class ScopedLock { public: - ScopedLock(Mutex &); + // Locks a mutex while this objects exists. + // + // If unlock = true, the working is reversed: + // the mutex is unlocked while this object exists. + ScopedLock(Mutex &, bool unlock = false); ~ScopedLock(); private: @@ -78,6 +82,7 @@ class ScopedLock ScopedLock& operator=(const ScopedLock&); Mutex &itsMutex; + const bool itsUnlock; }; @@ -159,18 +164,19 @@ inline bool Mutex::trylock() } -inline ScopedLock::ScopedLock(Mutex &mutex) +inline ScopedLock::ScopedLock(Mutex &mutex, bool unlock) : - itsMutex(mutex) + itsMutex(mutex), + itsUnlock(unlock) { - itsMutex.lock(); + itsUnlock ? itsMutex.unlock() : itsMutex.lock(); } inline ScopedLock::~ScopedLock() { try { - itsMutex.unlock(); + itsUnlock ? itsMutex.lock() : itsMutex.unlock(); } catch (std::exception &) {} } diff --git a/LCS/Common/test/tMutex.cc b/LCS/Common/test/tMutex.cc index 1128aecd4fc41c15fe66e874220c9c77ac2928e8..7822917e664eecc1dcaf937769b5c378c5bbe403 100644 --- a/LCS/Common/test/tMutex.cc +++ b/LCS/Common/test/tMutex.cc @@ -58,6 +58,13 @@ void test_simple(Mutex::Type type) { { ScopedLock sl(mutex); } + + { + // scoped locking and unlocking should be stackable + ScopedLock sl1(mutex, false); + ScopedLock sl2(mutex, true); + ScopedLock sl3(mutex, false); + } } void test_trylock(Mutex::Type type) {