Atlas Game Manager
A game manager for f95 and dlsite written in c++
Loading...
Searching...
No Matches
mainThread.hpp
Go to the documentation of this file.
1//
2// Created by kj16609 on 7/22/23.
3//
4
5#pragma once
6#ifndef ATLASGAMEMANAGER_MAINTHREAD_HPP
7#define ATLASGAMEMANAGER_MAINTHREAD_HPP
8
9#include <QMetaObject>
10#include <QObject>
11#include <QThread>
12#include <QTimer>
13
15#include "core/exceptions.hpp"
16
17namespace utils
18{
19 void setMainThread( QThread* thread );
20 QThread* mainThread();
21
22 template < typename Function, typename... Args >
23 FunctionReturn< Function > executeOnMain( Function&& func, Args&&... args )
24 {
25 QThread* main { mainThread() };
26 if ( main == nullptr )
27 throw AtlasException( "Tried to run executeOnMain without setting a main thread first!" );
28
29 if ( QThread::currentThread() == mainThread() )
30 {
31 //Execute as normal
32 return func( std::forward< Args >( args )... );
33 }
34 else
35 {
36 if constexpr ( std::same_as< FunctionReturn< Function >, void > )
37 {
38 //Fire and forget
39 QMetaObject::invokeMethod(
40 main,
41 [ func = std::forward< Function >( func ), args... ]() mutable -> void
42 {
43 try
44 {
45 func( std::forward< Args >( args )... );
46 }
47 catch ( ... )
48 {
49 //Eat and silence
50 }
51 },
52 Qt::QueuedConnection );
53 return;
54 }
55 else
56 {
57 auto promise { std::make_shared< QPromise< FunctionReturn< Function > > >() };
58
59 QMetaObject::invokeMethod(
60 main,
61 [ promise, func, args... ]() -> void
62 {
63 promise->addResult( func( std::forward< Args >( args )... ) );
64 promise->finish();
65 },
66 Qt::QueuedConnection );
67
68 auto future { promise->future() };
69 future.waitForFinished();
70 return future.result();
71 }
72 }
73 }
74
75} // namespace utils
76
77#endif //ATLASGAMEMANAGER_MAINTHREAD_HPP
FunctionDecomp< Func >::ResultType FunctionReturn
Definition FunctionDecomp.hpp:50
int main(int argc, char **argv)
Definition main.cpp:39
Definition mainThread.cpp:8
FunctionReturn< Function > executeOnMain(Function &&func, Args &&... args)
Definition mainThread.hpp:23
QThread * mainThread()
Definition mainThread.cpp:20
void setMainThread(QThread *ptr)
Definition mainThread.cpp:15
Definition exceptions.hpp:17