Advertisement
den4ik2003

Untitled

Aug 31st, 2023
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.89 KB | None | 0 0
  1. #pragma once
  2.  
  3. #include <twist/ed/stdlike/atomic.hpp>
  4. #include <twist/ed/wait/sys.hpp>
  5.  
  6. #include <cstdlib>
  7.  
  8. namespace stdlike {
  9.  
  10. class Mutex {
  11. public:
  12. Mutex() = default;
  13.  
  14. Mutex(Mutex&) = delete;
  15.  
  16. void Lock() {
  17. locked_threads_count_.fetch_add(1);
  18.  
  19. while (is_locked_.exchange(LockCond::locked) != LockCond::unlocked) {
  20. twist::ed::Wait(is_locked_, LockCond::locked);
  21. }
  22.  
  23. locked_threads_count_.fetch_sub(1);
  24. }
  25.  
  26. void Unlock() {
  27. auto wake_key = twist::ed::PrepareWake(is_locked_);
  28.  
  29. is_locked_.store(LockCond::unlocked);
  30.  
  31. if (locked_threads_count_.load() > 0) {
  32. twist::ed::WakeOne(wake_key);
  33. }
  34. }
  35.  
  36. private:
  37. enum LockCond { unlocked = 0, locked = 1 };
  38.  
  39. twist::ed::stdlike::atomic<uint32_t> locked_threads_count_{0};
  40. twist::ed::stdlike::atomic<uint32_t> is_locked_ = LockCond::unlocked;
  41. };
  42.  
  43. } // namespace stdlike
  44.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement