Debian Codegraph @

Source/Core/Common/WaitableFlag.h

raw symbols SCIP
1 // Copyright 2025 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 // Wrapper around Flag that lets callers wait for the flag to change.
5
6 #pragma once
7
8 #include <chrono>
9 #include <condition_variable>
10 #include <mutex>
11
12 #include "Common/Flag.h"
13
14 namespace Common
15 {
16 class WaitableFlag final
17 {
18 public:
19 void Set(bool value = true)
20 {
21 if (m_flag.TestAndSet(value))
22 {
23 // Lock and immediately unlock m_mutex.
24 {
25 // Holding the lock at any time between the change of our flag and notify call
26 // is sufficient to prevent a race where both of these actions
27 // happen between the other thread's predicate test and wait call
28 // which would cause wait to block until the next spurious wakeup or timeout.
29
30 // Unlocking before notification is a micro-optimization to prevent
31 // the notified thread from immediately blocking on the mutex.
32 std::lock_guard<std::mutex> lk(m_mutex);
33 }
34
35 m_condvar.notify_all();
36 }
37 }
38
39 void Reset() { Set(false); }
40
41 void Wait(bool expected_value)
42 {
43 if (m_flag.IsSet() == expected_value)
44 return;
45
46 std::unique_lock<std::mutex> lk(m_mutex);
47 m_condvar.wait(lk, [&] { return m_flag.IsSet() == expected_value; });
48 }
49
50 template <class Rep, class Period>
51 bool WaitFor(bool expected_value, const std::chrono::duration<Rep, Period>& rel_time)
52 {
53 if (m_flag.IsSet() == expected_value)
54 return true;
55
56 std::unique_lock<std::mutex> lk(m_mutex);
57 bool signaled =
58 m_condvar.wait_for(lk, rel_time, [&] { return m_flag.IsSet() == expected_value; });
59
60 return signaled;
61 }
62
63 private:
64 Flag m_flag;
65 std::condition_variable m_condvar;
66 std::mutex m_mutex;
67 };
68
69 } // namespace Common