From: Mukund Sivaraman Date: Mon, 15 Oct 2012 04:29:22 +0000 (+0530) Subject: [2198] Test the non-blocking variant of Mutex::Locker X-Git-Tag: trac2402_base~28^2~3 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=4ed683ce42d061905a4e5b06fcc1a38c64136e7a;p=thirdparty%2Fkea.git [2198] Test the non-blocking variant of Mutex::Locker --- diff --git a/src/lib/util/threads/tests/lock_unittest.cc b/src/lib/util/threads/tests/lock_unittest.cc index 0b4d3ce4ec..feabe3f29d 100644 --- a/src/lib/util/threads/tests/lock_unittest.cc +++ b/src/lib/util/threads/tests/lock_unittest.cc @@ -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