]> git.ipfire.org Git - thirdparty/kea.git/commitdiff
[2198] Test the non-blocking variant of Mutex::Locker
authorMukund Sivaraman <muks@isc.org>
Mon, 15 Oct 2012 04:29:22 +0000 (09:59 +0530)
committerMukund Sivaraman <muks@isc.org>
Mon, 15 Oct 2012 04:29:22 +0000 (09:59 +0530)
src/lib/util/threads/tests/lock_unittest.cc

index 0b4d3ce4ecffcac34a791e0e5e1e18daef2487bd..feabe3f29d8bdc1df6775c279acb149f8bc9c23f 100644 (file)
@@ -37,6 +37,45 @@ TEST(MutexTest, lockMultiple) {
         Mutex::Locker l2(mutex); // Attempt to lock again.
     }, isc::InvalidOperation);
     EXPECT_TRUE(mutex.locked()); // Debug-only build
+
+    // block=true explicitly.
+    Mutex mutex2;
+    EXPECT_FALSE(mutex2.locked()); // Debug-only build
+    Mutex::Locker l12(mutex2, true);
+    EXPECT_TRUE(mutex2.locked()); // Debug-only build
+}
+
+void*
+testThread(Mutex* mutex)
+{
+    // This should not block indefinitely, but throw AlreadyLocked.
+    // block=false (tryLock).
+    EXPECT_THROW({
+        Mutex::Locker l3(*mutex, false);
+    }, Mutex::Locker::AlreadyLocked);
+
+    EXPECT_TRUE(mutex->locked()); // Debug-only build
+
+    return NULL;
+}
+
+// Test the non-blocking variant using a second thread.
+TEST(MutexTest, lockNonBlocking) {
+    // block=false (tryLock).
+    Mutex mutex;
+    Mutex::Locker l1(mutex, false);
+    EXPECT_TRUE(mutex.locked()); // Debug-only build
+
+    // First, try another locker from the same thread.
+    EXPECT_THROW({
+        Mutex::Locker l2(mutex, false);
+    }, Mutex::Locker::AlreadyLocked);
+
+    EXPECT_TRUE(mutex.locked()); // Debug-only build
+
+    // Now try another locker from a different thread.
+    Thread thread(boost::bind(&testThread, &mutex));
+    thread.wait();
 }
 
 // Destroying a locked mutex is a bad idea as well