/** Boost thread shared_mutex test code. Copyright (c) 2013, Fredrik Orderud. */ #include #include using namespace boost; static void lock_shared (shared_mutex & m) { shared_lock lock(m); std::cout << "shared_thread has lock\n"; } static void lock_exclusive (shared_mutex & m) { unique_lock lock(m); std::cout << "exclusive_thread has lock\n"; } /** Test code to investigate the "pthread" shared_mutex exclusive_waiting_blocked state. define RESET_EXCLUSIVE_WAITING_BLOCKED to observe how a failed timed_lock affects */ void pthread_shared_mutex_tests () { shared_mutex m; thread exclusive_thread; thread shared_thread; { // acquire shared lock shared_lock lock(m); // exclusive lock request (will block) exclusive_thread = thread(lock_exclusive, ref(m)); // wait for exclusive_thread to be blocked (will trigger exclusive_waiting_blocked) this_thread::sleep(posix_time::milliseconds(100)); // shared lock request (will be blocked due to exclusive_waiting_blocked) shared_thread = thread(lock_shared, ref(m)); #ifdef RESET_EXCLUSIVE_WAITING_BLOCKED // reset exclusive_waiting_blocked (side-effect of failed timed_lock) // shared_thread will win in ~90% of the cases, since "lock" (acquired shared_lock) has not yet been released bool succeeded = m.timed_lock(posix_time::milliseconds(100)); BOOST_VERIFY(succeeded == false); #else // exclusive_thread and shared_thread will now compete for the mutex // excusive_thread will win in ~90% of the cases, since it's notified first #endif } // synchronize shared_thread.join(); exclusive_thread.join(); }