| 1 | // Copyright 2015 Dolphin Emulator Project |
| 2 | // SPDX-License-Identifier: GPL-2.0-or-later |
| 3 | |
| 4 | #pragma once |
| 5 | |
| 6 | #include <atomic> |
| 7 | #include <mutex> |
| 8 | #include <thread> |
| 9 | |
| 10 | #include "Common/Event.h" |
| 11 | #include "Common/Flag.h" |
| 12 | |
| 13 | namespace Common |
| 14 | { |
| 15 | // This class provides a synchronized loop. |
| 16 | // It's a thread-safe way to trigger a new iteration without busy loops. |
| 17 | // It's optimized for high-usage iterations which usually are already running while it's triggered |
| 18 | // often. |
| 19 | // Be careful when using Wait() and Wakeup() at the same time. Wait() may block forever while |
| 20 | // Wakeup() is called regularly. |
| 21 | class BlockingLoop |
| 22 | { |
| 23 | public: |
| 24 | enum class StopMode |
| 25 | { |
| 26 | NonBlock, |
| 27 | Block, |
| 28 | BlockAndGiveUp, |
| 29 | }; |
| 30 | |
| 31 | BlockingLoop() { m_stopped.Set(); } |
| 32 | ~BlockingLoop() { Stop(StopMode::BlockAndGiveUp); } |
| 33 | // Triggers to rerun the payload of the Run() function at least once again. |
| 34 | // This function will never block and is designed to finish as fast as possible. |
| 35 | void Wakeup() |
| 36 | { |
| 37 | // Already running, so no need for a wakeup. |
| 38 | // This is the common case, so try to get this as fast as possible. |
| 39 | if (m_running_state.load() >= STATE_NEED_EXECUTION) |
| 40 | return; |
| 41 | |
| 42 | // Mark that new data is available. If the old state will rerun the payload |
| 43 | // itself, we don't have to set the event to interrupt the worker. |
| 44 | if (m_running_state.exchange(STATE_NEED_EXECUTION) != STATE_SLEEPING) |
| 45 | return; |
| 46 | |
| 47 | // Else as the worker thread may sleep now, we have to set the event. |
| 48 | m_new_work_event.Set(); |
| 49 | } |
| 50 | |
| 51 | // Wait for a complete payload run after the last Wakeup() call. |
| 52 | // If stopped, this returns immediately. |
| 53 | void Wait() |
| 54 | { |
| 55 | // already done |
| 56 | if (IsDone()) |
| 57 | return; |
| 58 | |
| 59 | // notifying this event will only wake up one thread, so use a mutex here to |
| 60 | // allow only one waiting thread. And in this way, we get an event free wakeup |
| 61 | // but for the first thread for free |
| 62 | std::lock_guard<std::mutex> lk(m_wait_lock); |
| 63 | |
| 64 | // Wait for the worker thread to finish. |
| 65 | while (!IsDone()) |
| 66 | { |
| 67 | m_done_event.Wait(); |
| 68 | } |
| 69 | |
| 70 | // As we wanted to wait for the other thread, there is likely no work remaining. |
| 71 | // So there is no need for a busy loop any more. |
| 72 | m_may_sleep.Set(); |
| 73 | } |
| 74 | |
| 75 | // Wait for a complete payload run after the last Wakeup() call. |
| 76 | // This version will call a yield function every 100ms. |
| 77 | // If stopped, this returns immediately. |
| 78 | template <class Rep, class Period, typename Functor> |
| 79 | void WaitYield(const std::chrono::duration<Rep, Period>& rel_time, Functor yield_func) |
| 80 | { |
| 81 | // already done |
| 82 | if (IsDone()) |
| 83 | return; |
| 84 | |
| 85 | // notifying this event will only wake up one thread, so use a mutex here to |
| 86 | // allow only one waiting thread. And in this way, we get an event free wakeup |
| 87 | // but for the first thread for free |
| 88 | std::lock_guard<std::mutex> lk(m_wait_lock); |
| 89 | |
| 90 | // Wait for the worker thread to finish. |
| 91 | while (!IsDone()) |
| 92 | { |
| 93 | if (!m_done_event.WaitFor(rel_time)) |
| 94 | yield_func(); |
| 95 | } |
| 96 | |
| 97 | // As we wanted to wait for the other thread, there is likely no work remaining. |
| 98 | // So there is no need for a busy loop any more. |
| 99 | m_may_sleep.Set(); |
| 100 | } |
| 101 | |
| 102 | // Half start the worker. |
| 103 | // So this object is in a running state and Wait() will block until the worker calls Run(). |
| 104 | // This may be called from any thread and is supposed to be called at least once before Wait() is |
| 105 | // used. |
| 106 | void Prepare() |
| 107 | { |
| 108 | // There is a race condition if the other threads call this function while |
| 109 | // the loop thread is initializing. Using this lock will ensure a valid state. |
| 110 | std::lock_guard<std::mutex> lk(m_prepare_lock); |
| 111 | |
| 112 | if (!m_stopped.TestAndClear()) |
| 113 | return; |
| 114 | m_running_state.store( |
| 115 | STATE_LAST_EXECUTION); // so the payload will only be executed once without any Wakeup call |
| 116 | m_shutdown.Clear(); |
| 117 | m_may_sleep.Set(); |
| 118 | } |
| 119 | |
| 120 | // Main loop of this object. |
| 121 | // The payload callback is called at least as often as it's needed to match the Wakeup() |
| 122 | // requirements. |
| 123 | // The optional timeout parameter is a timeout for how periodically the payload should be called. |
| 124 | // Use timeout = 0 to run without a timeout at all. |
| 125 | template <class F> |
| 126 | void Run(F payload, int64_t timeout = 0) |
| 127 | { |
| 128 | // Asserts that Prepare is called at least once before we enter the loop. |
| 129 | // But a good implementation should call this before already. |
| 130 | Prepare(); |
| 131 | |
| 132 | while (!m_shutdown.IsSet()) |
| 133 | { |
| 134 | payload(); |
| 135 | |
| 136 | switch (m_running_state.load()) |
| 137 | { |
| 138 | case STATE_NEED_EXECUTION: |
| 139 | // We won't get notified while we are in the STATE_NEED_EXECUTION state, so maybe Wakeup was |
| 140 | // called. |
| 141 | // So we have to assume on finishing the STATE_NEED_EXECUTION state, that there may be some |
| 142 | // remaining tasks. |
| 143 | // To process this tasks, we call the payload again within the STATE_LAST_EXECUTION state. |
| 144 | m_running_state--; |
| 145 | break; |
| 146 | |
| 147 | case STATE_LAST_EXECUTION: |
| 148 | // If we're still in the STATE_LAST_EXECUTION state, then Wakeup wasn't called within the |
| 149 | // last |
| 150 | // execution of the payload. This means we should be ready now. |
| 151 | // But bad luck, Wakeup may have been called right now. So break and rerun the payload |
| 152 | // if the state was touched. |
| 153 | if (m_running_state-- != STATE_LAST_EXECUTION) |
| 154 | break; |
| 155 | |
| 156 | // Else we're likely in the STATE_DONE state now, so wakeup the waiting threads right now. |
| 157 | // However, if we're not in the STATE_DONE state any more, the event should also be |
| 158 | // triggered so that we'll skip the next waiting call quite fast. |
| 159 | m_done_event.Set(); |
| 160 | [[fallthrough]]; |
| 161 | |
| 162 | case STATE_DONE: |
| 163 | // We're done now. So time to check if we want to sleep or if we want to stay in a busy |
| 164 | // loop. |
| 165 | if (m_may_sleep.TestAndClear()) |
| 166 | { |
| 167 | // Try to set the sleeping state. |
| 168 | if (m_running_state-- != STATE_DONE) |
| 169 | break; |
| 170 | } |
| 171 | else |
| 172 | { |
| 173 | // Busy loop. |
| 174 | break; |
| 175 | } |
| 176 | [[fallthrough]]; |
| 177 | |
| 178 | case STATE_SLEEPING: |
| 179 | // Just relax |
| 180 | if (timeout > 0) |
| 181 | { |
| 182 | m_new_work_event.WaitFor(std::chrono::milliseconds(timeout)); |
| 183 | } |
| 184 | else |
| 185 | { |
| 186 | m_new_work_event.Wait(); |
| 187 | } |
| 188 | break; |
| 189 | } |
| 190 | } |
| 191 | |
| 192 | // Shutdown down, so get a safe state |
| 193 | m_running_state.store(STATE_DONE); |
| 194 | m_stopped.Set(); |
| 195 | |
| 196 | // Wake up the last Wait calls. |
| 197 | m_done_event.Set(); |
| 198 | } |
| 199 | |
| 200 | // Quits the main loop. |
| 201 | // By default, it will wait until the main loop quits. |
| 202 | // Be careful to not use the blocking way within the payload of the Run() method. |
| 203 | void Stop(StopMode mode = StopMode::Block) |
| 204 | { |
| 205 | if (m_stopped.IsSet()) |
| 206 | return; |
| 207 | |
| 208 | m_shutdown.Set(); |
| 209 | |
| 210 | // We have to interrupt the sleeping call to let the worker shut down soon. |
| 211 | Wakeup(); |
| 212 | |
| 213 | switch (mode) |
| 214 | { |
| 215 | case StopMode::NonBlock: |
| 216 | break; |
| 217 | case StopMode::Block: |
| 218 | Wait(); |
| 219 | break; |
| 220 | case StopMode::BlockAndGiveUp: |
| 221 | WaitYield(std::chrono::milliseconds(100), [&] { |
| 222 | // If timed out, assume no one will come along to call Run, so force a break |
| 223 | m_stopped.Set(); |
| 224 | }); |
| 225 | break; |
| 226 | } |
| 227 | } |
| 228 | |
| 229 | bool IsRunning() const { return !m_stopped.IsSet() && !m_shutdown.IsSet(); } |
| 230 | bool IsDone() const { return m_stopped.IsSet() || m_running_state.load() <= STATE_DONE; } |
| 231 | // This function should be triggered regularly over time so |
| 232 | // that we will fall back from the busy loop to sleeping. |
| 233 | void AllowSleep() { m_may_sleep.Set(); } |
| 234 | |
| 235 | private: |
| 236 | std::mutex m_wait_lock; |
| 237 | std::mutex m_prepare_lock; |
| 238 | |
| 239 | Flag m_stopped; // If this is set, Wait() shall not block. |
| 240 | Flag m_shutdown; // If this is set, the loop shall end. |
| 241 | |
| 242 | Event m_new_work_event; |
| 243 | Event m_done_event; |
| 244 | |
| 245 | enum RUNNING_TYPE |
| 246 | { |
| 247 | STATE_SLEEPING = 0, |
| 248 | STATE_DONE = 1, |
| 249 | STATE_LAST_EXECUTION = 2, |
| 250 | STATE_NEED_EXECUTION = 3 |
| 251 | }; |
| 252 | std::atomic<int> m_running_state; // must be of type RUNNING_TYPE |
| 253 | |
| 254 | Flag m_may_sleep; // If this is set, we fall back from the busy loop to an event based |
| 255 | // synchronization. |
| 256 | }; |
| 257 | } // namespace Common |