Debian Codegraph @

Source/Core/Common/OneShotEvent.h

raw symbols SCIP
1 // Copyright 2025 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #pragma once
5
6 #include <chrono>
7 #include <memory>
8 #include <semaphore>
9
10 #include "Common/Functional.h"
11
12 namespace Common
13 {
14
15 // A one-time-use single-producer single-consumer thread synchronization class.
16 // Safe when `Set` will cause a `Wait`ing thread to immediately destruct the event itself.
17 class OneShotEvent
18 {
19 public:
20 // One thread should call Set() exactly once.
21 void Set() { m_semaphore.release(1); }
22
23 // One thread may call Wait() once or WaitFor() until it returns true.
24
25 void Wait() { m_semaphore.acquire(); }
26
27 template <typename Rep, typename Period>
28 bool WaitFor(const std::chrono::duration<Rep, Period>& rel_time)
29 {
30 return m_semaphore.try_acquire_for(rel_time);
31 }
32
33 private:
34 std::binary_semaphore m_semaphore{0};
35 };
36
37 // Invokes Set() on the given object upon destruction.
38 template <typename EventType>
39 class ScopedSetter
40 {
41 public:
42 ScopedSetter() = default;
43 explicit ScopedSetter(EventType* ptr) : m_ptr{ptr} {}
44
45 // Forgets the object without invoking Set().
46 void Dismiss() { m_ptr.release(); }
47
48 private:
49 // Leveraging unique_ptr conveniently makes this class move-only.
50 // It does no actual deletion, just calls Set().
51 using NonOwningSetOnDeletePtr = std::unique_ptr<EventType, InvokerOf<&EventType::Set>>;
52 NonOwningSetOnDeletePtr m_ptr;
53 };
54
55 } // namespace Common