summaryrefslogtreecommitdiff
path: root/Source/Core/VideoCommon/AsyncRequests.h
blob: 1c72b55b8596d6ff225e34c92c6ef9be87994c57 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// Copyright 2015 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#pragma once

#include <condition_variable>
#include <functional>
#include <future>
#include <mutex>
#include <queue>

#include "Common/Flag.h"
#include "Common/Functional.h"

struct EfbPokeData;
class PointerWrap;

class AsyncRequests
{
public:
  AsyncRequests();

  void PullEvents()
  {
    if (!m_empty.IsSet())
      PullEventsInternal();
  }
  void WaitForEmptyQueue();
  void SetEnable(bool enable);
  void SetPassthrough(bool enable);

  template <typename F>
  void PushEvent(F&& callback)
  {
    std::unique_lock<std::mutex> lock(m_mutex);

    if (m_passthrough)
    {
      std::invoke(callback);
      return;
    }

    QueueEvent(Event{std::forward<F>(callback)});
  }

  template <typename F>
  auto PushBlockingEvent(F&& callback) -> std::invoke_result_t<F>
  {
    std::unique_lock<std::mutex> lock(m_mutex);

    if (m_passthrough)
      return std::invoke(callback);

    std::packaged_task task{std::forward<F>(callback)};
    QueueEvent(Event{[&] { task(); }});

    lock.unlock();
    return task.get_future().get();
  }

  static AsyncRequests* GetInstance() { return &s_singleton; }

private:
  using Event = Common::MoveOnlyFunction<void()>;

  void QueueEvent(Event&& event);

  void PullEventsInternal();

  static AsyncRequests s_singleton;

  Common::Flag m_empty;
  std::queue<Event> m_queue;
  std::mutex m_mutex;
  std::condition_variable m_cond;

  bool m_enable = false;
  bool m_passthrough = true;
};