Browse Source

[2198] Test that locks work from threads

This test fails now because there's no mutual exclusion among threads
in the implementation.
Mukund Sivaraman 12 years ago
parent
commit
2d014223ce

+ 1 - 0
src/lib/util/tests/Makefile.am

@@ -46,6 +46,7 @@ run_unittests_CPPFLAGS = $(AM_CPPFLAGS) $(GTEST_INCLUDES)
 run_unittests_LDFLAGS = $(AM_LDFLAGS) $(GTEST_LDFLAGS)
 
 run_unittests_LDADD = $(top_builddir)/src/lib/util/libb10-util.la
+run_unittests_LDADD += $(top_builddir)/src/lib/util/threads/libb10-threads.la
 run_unittests_LDADD += $(top_builddir)/src/lib/util/io/libb10-util-io.la
 run_unittests_LDADD += \
 	$(top_builddir)/src/lib/util/unittests/libutil_unittests.la

+ 48 - 1
src/lib/util/tests/interprocess_sync_file_unittest.cc

@@ -12,10 +12,15 @@
 // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 // PERFORMANCE OF THIS SOFTWARE.
 
-#include "util/interprocess_sync_file.h"
+#include <util/interprocess_sync_file.h>
+#include <util/threads/thread.h>
+
 #include <gtest/gtest.h>
+#include <boost/bind.hpp>
+
 #include <unistd.h>
 
+using namespace isc::util::thread;
 using namespace std;
 
 namespace isc {
@@ -108,6 +113,48 @@ TEST(InterprocessSyncFileTest, TestLock) {
   EXPECT_EQ (0, unlink(TEST_DATA_TOPBUILDDIR "/test_lockfile"));
 }
 
+void*
+threadTest(bool* locked)
+{
+    InterprocessSyncFile sync2("test");
+    InterprocessSyncLocker locker2(sync2);
+
+    *locked = !locker2.tryLock();
+
+    return NULL;
+}
+
+TEST(InterprocessSyncFileTest, TestLockThreaded) {
+    InterprocessSyncFile sync("test");
+    InterprocessSyncLocker locker(sync);
+
+    EXPECT_FALSE(locker.isLocked());
+    EXPECT_TRUE(locker.lock());
+    EXPECT_TRUE(locker.isLocked());
+
+    bool locked_in_other_thread = false;
+
+    // Here, we check that a lock has been taken by creating a new
+    // thread and checking from the new thread that a lock exists. The
+    // lock attempt must fail to pass our check.
+    Thread thread(boost::bind(&threadTest, &locked_in_other_thread));
+    thread.wait();
+
+    EXPECT_TRUE(locked_in_other_thread);
+
+    // Release the lock and try again. This time, the attempt must pass.
+
+    EXPECT_TRUE(locker.unlock());
+    EXPECT_FALSE(locker.isLocked());
+
+    Thread thread2(boost::bind(&threadTest, &locked_in_other_thread));
+    thread2.wait();
+
+    EXPECT_FALSE(locked_in_other_thread);
+
+    EXPECT_EQ (0, unlink(TEST_DATA_TOPBUILDDIR "/test_lockfile"));
+}
+
 TEST(InterprocessSyncFileTest, TestMultipleFilesDirect) {
   InterprocessSyncFile sync("test1");
   InterprocessSyncLocker locker(sync);