| 1 | // Copyright 2014 Dolphin Emulator Project |
| 2 | // SPDX-License-Identifier: GPL-2.0-or-later |
| 3 | |
| 4 | // Multithreaded event class. This allows waiting in a thread for an event to |
| 5 | // be triggered in another thread. While waiting, the CPU will be available for |
| 6 | // other tasks. |
| 7 | // * Set(): triggers the event and wakes up the waiting thread. |
| 8 | // * Wait(): waits for the event to be triggered. |
| 9 | // * Reset(): tries to reset the event before the waiting thread sees it was |
| 10 | // triggered. Usually a bad idea. |
| 11 | |
| 12 | #pragma once |
| 13 | |
| 14 | #include <chrono> |
| 15 | #include <condition_variable> |
| 16 | #include <mutex> |
| 17 | |
| 18 | #include "Common/Flag.h" |
| 19 | |
| 20 | namespace Common |
| 21 | { |
| 22 | class Event final |
| 23 | { |
| 24 | public: |
| 25 | void Set() |
| 26 | { |
| 27 | if (m_flag.TestAndSet()) |
| 28 | { |
| 29 | // Lock and immediately unlock m_mutex. |
| 30 | { |
| 31 | // Holding the lock at any time between the change of our flag and notify call |
| 32 | // is sufficient to prevent a race where both of these actions |
| 33 | // happen between the other thread's predicate test and wait call |
| 34 | // which would cause wait to block until the next spurious wakeup or timeout. |
| 35 | |
| 36 | // Unlocking before notification is a micro-optimization to prevent |
| 37 | // the notified thread from immediately blocking on the mutex. |
| 38 | std::lock_guard<std::mutex> lk(m_mutex); |
| 39 | } |
| 40 | |
| 41 | m_condvar.notify_one(); |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | void Wait() |
| 46 | { |
| 47 | if (m_flag.TestAndClear()) |
| 48 | return; |
| 49 | |
| 50 | std::unique_lock<std::mutex> lk(m_mutex); |
| 51 | m_condvar.wait(lk, [&] { return m_flag.TestAndClear(); }); |
| 52 | } |
| 53 | |
| 54 | template <class Rep, class Period> |
| 55 | bool WaitFor(const std::chrono::duration<Rep, Period>& rel_time) |
| 56 | { |
| 57 | if (m_flag.TestAndClear()) |
| 58 | return true; |
| 59 | |
| 60 | std::unique_lock<std::mutex> lk(m_mutex); |
| 61 | bool signaled = m_condvar.wait_for(lk, rel_time, [&] { return m_flag.TestAndClear(); }); |
| 62 | |
| 63 | return signaled; |
| 64 | } |
| 65 | |
| 66 | void Reset() |
| 67 | { |
| 68 | // no other action required, since wait loops on |
| 69 | // the predicate and any lingering signal will get |
| 70 | // cleared on the first iteration |
| 71 | m_flag.Clear(); |
| 72 | } |
| 73 | |
| 74 | private: |
| 75 | Flag m_flag; |
| 76 | std::condition_variable m_condvar; |
| 77 | std::mutex m_mutex; |
| 78 | }; |
| 79 | |
| 80 | } // namespace Common |