Advertisement
Guest User

Untitled

a guest
Feb 23rd, 2020
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.81 KB | None | 0 0
  1. #pragma once
  2. #include <mutex>
  3.  
  4. class RWLock {
  5. public:
  6. template <class Func>
  7. void Read(Func func) {
  8. read_.lock();
  9. ++blocked_readers_;
  10. if (blocked_readers_ == 1) {
  11. global_.lock();
  12. }
  13. read_.unlock();
  14. try {
  15. func();
  16. } catch (...) {
  17. EndRead();
  18. throw;
  19. }
  20. EndRead();
  21. }
  22.  
  23. template <class Func>
  24. void Write(Func func) {
  25. std::lock_guard<std::mutex> lock(global_);
  26. func();
  27. }
  28.  
  29. private:
  30. std::mutex read_;
  31. std::mutex global_;
  32. int blocked_readers_ = 0;
  33.  
  34. void EndRead() {
  35. read_.lock();
  36. --blocked_readers_;
  37. if (!blocked_readers_) {
  38. global_.unlock();
  39. }
  40. read_.unlock();
  41. }
  42. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement