Browse Source

[2202] Debug-only method Mutex::locked

It can be used to check the thing is locked.
Michal 'vorner' Vaner 12 years ago
parent
commit
7cd33029c6

+ 6 - 0
src/lib/util/threads/lock.cc

@@ -136,6 +136,12 @@ Mutex::unlock() {
     }
 }
 
+// TODO: Disable in non-debug build
+bool
+Mutex::locked() const {
+    return (impl_->locked != 0);
+}
+
 }
 }
 }

+ 8 - 0
src/lib/util/threads/lock.h

@@ -115,6 +115,14 @@ public:
     private:
         Mutex* mutex_;
     };
+    /// \brief If the mutex is currently locked
+    ///
+    /// This is debug aiding method only. And it might be unavailable in
+    /// non-debug build (because keeping the state might be needlesly
+    /// slow).
+    ///
+    /// \todo Disable in non-debug build
+    bool locked() const;
 private:
     friend class Locker;
     struct Impl;

+ 5 - 0
src/lib/util/threads/tests/lock_unittest.cc

@@ -27,7 +27,9 @@ namespace {
 // Test a recursive mutex can be locked multiple times
 TEST(MutexTest, recursiveLockMultiple) {
     Mutex mutex(true);
+    EXPECT_FALSE(mutex.locked()); // Debug-only build
     Mutex::Locker l1(mutex);
+    EXPECT_TRUE(mutex.locked()); // Debug-only build
     Mutex::Locker l2(mutex);
     Mutex::Locker l3(mutex);
     Mutex::Locker l4(mutex);
@@ -39,10 +41,13 @@ TEST(MutexTest, lockMultiple) {
     // TODO: Once we support non-debug mutexes, disable the test if we compile
     // with them.
     Mutex mutex;
+    EXPECT_FALSE(mutex.locked()); // Debug-only build
     Mutex::Locker l1(mutex);
+    EXPECT_TRUE(mutex.locked()); // Debug-only build
     EXPECT_THROW({
         Mutex::Locker l2(mutex); // Attempt to lock again.
     }, isc::InvalidOperation);
+    EXPECT_TRUE(mutex.locked()); // Debug-only build
 }
 
 // Destroying a locked mutex is a bad idea as well