Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #pragma once
- #include <twist/ed/stdlike/atomic.hpp>
- #include <twist/ed/wait/sys.hpp>
- #include <cstdlib>
- namespace stdlike {
- class Mutex {
- public:
- Mutex() = default;
- Mutex(Mutex&) = delete;
- void Lock() {
- locked_threads_count_.fetch_add(1);
- while (is_locked_.exchange(LockCond::locked) != LockCond::unlocked) {
- twist::ed::Wait(is_locked_, LockCond::locked);
- }
- locked_threads_count_.fetch_sub(1);
- }
- void Unlock() {
- auto wake_key = twist::ed::PrepareWake(is_locked_);
- is_locked_.store(LockCond::unlocked);
- if (locked_threads_count_.load() > 0) {
- twist::ed::WakeOne(wake_key);
- }
- }
- private:
- enum LockCond { unlocked = 0, locked = 1 };
- twist::ed::stdlike::atomic<uint32_t> locked_threads_count_{0};
- twist::ed::stdlike::atomic<uint32_t> is_locked_ = LockCond::unlocked;
- };
- } // namespace stdlike
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement