/** Test code for extension of boost::shared_mutex with support for different priority policies. Copyright (c) 2012, Fredrik Orderud. */ #include #include #include "shared_pri_mutex.hpp" using namespace boost; using namespace boost_ext; template void lock_shared (mutex_t & m, bool & block_unlock) { shared_lock lock(m); while (block_unlock) this_thread::sleep(posix_time::milliseconds(1)); } template void lock_exclusive (mutex_t & m, bool & block_unlock) { unique_lock lock(m); while (block_unlock) this_thread::sleep(posix_time::milliseconds(1)); } template void test_mutex_priority (priority_policy priority) { mutex_t m; thread shared_t; thread exclusive_t; bool block_unlock = true; { // local lock to block other lock requests unique_lock lock(m); shared_t = thread(lock_shared, ref(m), ref(block_unlock)); exclusive_t = thread(lock_exclusive, ref(m), ref(block_unlock)); // wait until both threads are blocked while ( (m.get_state().shared_request_count != 1) || (m.get_state().exclusive_request_count != 2) ) this_thread::sleep(posix_time::milliseconds(1)); // either shared or exclusive lock will now be taken on local lock destruction } if (priority == SHARED_PRIORITY) { // wait until shared lock is taken (deadlocks if exclusive lock is taken) while (!m.get_state().shared_count) this_thread::sleep(posix_time::milliseconds(1)); } else if (priority == EXCLUSIVE_PRIORITY) { // wait until exclusive lock is taken (deadlocks if shared lock is taken) while (!m.get_state().exclusive) this_thread::sleep(posix_time::milliseconds(1)); } // enable unlocks block_unlock = false; // synchronize shared_t.join(); exclusive_t.join(); } void test_unspecified_priority () { typedef shared_pri_mutex<> mutex_t; mutex_t m; { // verify that multiple shared-locks can be taken simultaneously shared_lock lock1(m); shared_lock lock2(m); } { // verify that one exclusive-locks can be taken unique_lock lock(m); } } int main () { // test shared-priority mutex test_mutex_priority >(SHARED_PRIORITY); //test_mutex_priority >(EXCLUSIVE_PRIORITY); // uncomment to provoke deadlock // test exclusive-priority mutex test_mutex_priority >(EXCLUSIVE_PRIORITY); //test_mutex_priority >(SHARED_PRIORITY); // uncomment to provoke deadlock test_unspecified_priority(); return 0; }