2017-06-07 10:09:24 +02:00
|
|
|
#pragma once
|
2017-01-04 15:12:31 +01:00
|
|
|
|
2017-06-07 10:09:24 +02:00
|
|
|
#include <QCoreApplication>
|
2017-01-04 15:12:31 +01:00
|
|
|
|
2017-01-18 04:52:47 +01:00
|
|
|
#include <QRunnable>
|
|
|
|
#include <QThreadPool>
|
2017-06-07 10:09:24 +02:00
|
|
|
|
2017-01-18 21:30:23 +01:00
|
|
|
#include <functional>
|
2017-01-18 04:52:47 +01:00
|
|
|
|
2017-04-12 17:46:44 +02:00
|
|
|
#define async_exec(a) QThreadPool::globalInstance()->start(new LambdaRunnable(a));
|
2017-01-18 21:30:23 +01:00
|
|
|
|
2017-06-07 10:09:24 +02:00
|
|
|
class LambdaRunnable : public QRunnable
|
|
|
|
{
|
2017-01-18 21:30:23 +01:00
|
|
|
public:
|
|
|
|
LambdaRunnable(std::function<void()> action)
|
|
|
|
{
|
|
|
|
this->action = action;
|
|
|
|
}
|
|
|
|
|
2017-04-12 17:46:44 +02:00
|
|
|
void run()
|
2017-01-18 21:30:23 +01:00
|
|
|
{
|
|
|
|
this->action();
|
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
|
|
|
std::function<void()> action;
|
|
|
|
};
|
2017-12-16 01:57:34 +01:00
|
|
|
|
|
|
|
// Taken from
|
|
|
|
// https://stackoverflow.com/questions/21646467/how-to-execute-a-functor-or-a-lambda-in-a-given-thread-in-qt-gcd-style
|
|
|
|
// Qt 5/4 - preferred, has least allocations
|
|
|
|
template <typename F>
|
|
|
|
static void postToThread(F &&fun, QObject *obj = qApp)
|
|
|
|
{
|
|
|
|
struct Event : public QEvent {
|
|
|
|
using Fun = typename std::decay<F>::type;
|
|
|
|
Fun fun;
|
|
|
|
Event(Fun &&fun)
|
|
|
|
: QEvent(QEvent::None)
|
|
|
|
, fun(std::move(fun))
|
|
|
|
{
|
|
|
|
}
|
|
|
|
Event(const Fun &fun)
|
|
|
|
: QEvent(QEvent::None)
|
|
|
|
, fun(fun)
|
|
|
|
{
|
|
|
|
}
|
|
|
|
~Event()
|
|
|
|
{
|
|
|
|
fun();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
QCoreApplication::postEvent(obj, new Event(std::forward<F>(fun)));
|
|
|
|
}
|