forked from nst1911/thread-safe-qjsengine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththreadsafeqjsengine.h
39 lines (33 loc) · 985 Bytes
/
threadsafeqjsengine.h
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
#ifndef THREADSAFEQJSENGINE_H
#define THREADSAFEQJSENGINE_H
#include <QJSEngine>
#include <QThread>
namespace ThreadSafeQJSEngine {
template <typename F>
auto call(QJSEngine* engine, F&& f) -> typename std::enable_if<!std::is_void<decltype(f())>::value, decltype(f())>::type
{
if (QThread::currentThread() != engine->thread())
{
decltype(f()) result;
QMetaObject::invokeMethod(engine, std::forward<F>(f), Qt::BlockingQueuedConnection, &result);
return result;
}
else
{
return std::forward<F>(f)();
}
}
template <typename F>
auto call(QJSEngine* engine, F&& f) -> typename std::enable_if<std::is_void<decltype(f())>::value, void>::type
{
if (QThread::currentThread() != engine->thread())
{
QMetaObject::invokeMethod(engine, std::forward<F>(f), Qt::BlockingQueuedConnection);
}
else
{
std::forward<F>(f)();
}
}
};
#endif // THREADSAFEQJSENGINE_H