unit-reader-writer-lock.cpp 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #include <catch2/catch.hpp>
  2. #include <iostream>
  3. #include <thread>
  4. #include <mutex>
  5. #include <shared_mutex>
  6. #include <atomic>
  7. #include <condition_variable>
  8. #include <gul/utils/writer_preferred_shared_mutex.h>
  9. using RWLock = gul::writer_preferred_shared_mutex;
  10. SCENARIO("TEST")
  11. {
  12. RWLock lock;
  13. auto _reader= [&lock]()
  14. {
  15. for(int i=0;i<50;i++)
  16. {
  17. {
  18. std::shared_lock<RWLock> L(lock);
  19. std::this_thread::sleep_for( std::chrono::milliseconds(100+rand()%25));
  20. }
  21. }
  22. };
  23. auto _writer = [&lock]()
  24. {
  25. std::this_thread::sleep_for(std::chrono::milliseconds(rand()%500));
  26. for(int i=0;i<5;i++)
  27. {
  28. {
  29. std::cout << "Readers Waiting: " << lock.get_reader_count() << std::endl;
  30. std::unique_lock<RWLock> L(lock);
  31. std::this_thread::sleep_for(std::chrono::milliseconds(100+rand()%25));
  32. }
  33. std::this_thread::sleep_for(std::chrono::milliseconds(1000+rand()%500));
  34. }
  35. };
  36. std::thread R1(_reader);
  37. std::thread R2(_reader);
  38. std::thread R3(_reader);
  39. std::thread R4(_reader);
  40. std::thread R5(_writer);
  41. std::thread R6(_writer);
  42. R1.join();
  43. R2.join();
  44. R3.join();
  45. R4.join();
  46. R5.join();
  47. R6.join();
  48. }