Chatterino
PostToThread.hpp
Go to the documentation of this file.
1 #pragma once
2 
4 
5 #include <QCoreApplication>
6 #include <QRunnable>
7 #include <QThreadPool>
8 
9 #include <functional>
10 
11 #define async_exec(a) \
12  QThreadPool::globalInstance()->start(new LambdaRunnable(a));
13 
14 namespace chatterino {
15 
16 class LambdaRunnable : public QRunnable
17 {
18 public:
19  LambdaRunnable(std::function<void()> action)
20  {
21  this->action_ = std::move(action);
22  }
23 
24  void run()
25  {
26  this->action_();
27  }
28 
29 private:
30  std::function<void()> action_;
31 };
32 
33 // Taken from
34 // https://stackoverflow.com/questions/21646467/how-to-execute-a-functor-or-a-lambda-in-a-given-thread-in-qt-gcd-style
35 // Qt 5/4 - preferred, has least allocations
36 template <typename F>
37 static void postToThread(F &&fun, QObject *obj = qApp)
38 {
39  struct Event : public QEvent {
40  using Fun = typename std::decay<F>::type;
41  Fun fun;
42  Event(Fun &&fun)
43  : QEvent(QEvent::None)
44  , fun(std::move(fun))
45  {
46  }
47  Event(const Fun &fun)
48  : QEvent(QEvent::None)
49  , fun(fun)
50  {
51  }
52  ~Event() override
53  {
54  fun();
55  }
56  };
57  QCoreApplication::postEvent(obj, new Event(std::forward<F>(fun)));
58 }
59 
60 template <typename F>
61 static void runInGuiThread(F &&fun)
62 {
63  if (isGuiThread())
64  {
65  fun();
66  }
67  else
68  {
69  postToThread(fun);
70  }
71 }
72 
73 } // namespace chatterino
Definition: Application.cpp:48
void run()
Definition: PostToThread.hpp:24
Definition: PostToThread.hpp:16
LambdaRunnable(std::function< void()> action)
Definition: PostToThread.hpp:19