recursive_shared_mutex_test.hxx 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #ifndef RECURSIVE_SHARED_MUTEX_TEST_HXX
  2. #define RECURSIVE_SHARED_MUTEX_TEST_HXX
  3. #include "libbinom/include/utils/shared_recursive_mutex_wrapper.hxx"
  4. #include "test/tester.hxx"
  5. #include <list>
  6. #include <thread>
  7. std::shared_mutex shared_mtx;
  8. void subwriter();
  9. bool is_valid_data = true;
  10. void subreader() {
  11. GRP_PUSH
  12. shared_recursive_mtx::SharedRecursiveLock lock(&shared_mtx, shared_recursive_mtx::MtxLockType::shared_locked);
  13. static thread_local int recursion_depth = 0;
  14. TEST(is_valid_data);
  15. if (++recursion_depth <= 20) subreader();
  16. else subwriter();
  17. TEST(is_valid_data);
  18. GRP_POP
  19. }
  20. void subwriter() {
  21. GRP_PUSH
  22. shared_recursive_mtx::SharedRecursiveLock lock(&shared_mtx, shared_recursive_mtx::MtxLockType::unique_locked);
  23. static thread_local int recursion_depth = 0;
  24. PRINT_RUN(is_valid_data = false);
  25. if (++recursion_depth <= 10) subwriter();
  26. PRINT_RUN(is_valid_data = true);
  27. GRP_POP
  28. }
  29. void testRecursiveSharedMutex() {
  30. RAIIPerfomanceTest test_perf("Recursive shared mutex test: ");
  31. SEPARATOR
  32. TEST_ANNOUNCE(RecursiveSharedMutex test);
  33. shared_mtx.lock();
  34. std::list<std::thread> threads;
  35. for(unsigned int i = 0; i < std::thread::hardware_concurrency(); ++i)
  36. threads.emplace_back(subreader);
  37. shared_mtx.unlock();
  38. for(auto& thread : threads) thread.join();
  39. }
  40. #endif // RECURSIVE_SHARED_MUTEX_TEST_HXX