15 #include <QMutexLocker>
16 #include <QFutureInterface>
28 std::atomic_bool IsPaused_ {
false };
30 QMutex FunctionsMutex_;
31 QList<std::function<void ()>> Functions_;
33 using QThread::QThread;
35 void SetPaused (
bool);
38 QFuture<std::result_of_t<F ()>> ScheduleImpl (F func)
41 iface.reportStarted ();
43 auto reporting = [func, iface] ()
mutable
45 ReportFutureResult (iface, func);
49 QMutexLocker locker { &FunctionsMutex_ };
50 Functions_ << reporting;
55 return iface.future ();
58 template<
typename F,
typename... Args>
59 QFuture<std::result_of_t<F (Args...)>> ScheduleImpl (F
f, Args&&... args)
61 return ScheduleImpl ([
f, args...] ()
mutable { return std::invoke (f, args...); });
64 virtual size_t GetQueueSize ();
68 virtual
void Initialize () = 0;
69 virtual
void Cleanup () = 0;
78 template<
typename WorkerType>
79 struct InitializerBase
81 virtual std::unique_ptr<WorkerType> Initialize () = 0;
83 virtual ~InitializerBase () =
default;
86 template<
typename WorkerType,
typename... Args>
89 std::tuple<Args...> Args_;
92 : Args_ { std::move (tuple) }
96 std::unique_ptr<WorkerType> Initialize ()
override
98 return std::apply ([] (
auto&&... args) {
return std::make_unique<WorkerType> (std::forward<Args> (args)...); }, Args_);
102 template<
typename WorkerType>
105 std::unique_ptr<WorkerType> Initialize ()
override
107 return std::make_unique<WorkerType> ();
112 template<
typename WorkerType>
115 std::atomic_bool IsAutoQuit_ {
false };
116 unsigned long QuitWait_ = 2000;
118 using W = WorkerType;
120 std::unique_ptr<WorkerType> Worker_;
122 std::unique_ptr<detail::InitializerBase<WorkerType>> Initializer_;
126 , Initializer_ { std::make_unique<detail::Initializer<WorkerType>> () }
130 template<
typename... Args>
133 , Initializer_ { std::make_unique<detail::Initializer<WorkerType, std::decay_t<Args>...>> (std::tuple<std::decay_t<Args>...> { args... }) }
140 typename = std::enable_if_t<
141 !std::is_base_of<QObject, std::remove_pointer_t<std::decay_t<Head>>>::value
145 :
WorkerThread {
static_cast<QObject*
> (
nullptr), head, rest... }
158 qWarning () << Q_FUNC_INFO
159 <<
"thread is still running";
162 void SetAutoQuit (
bool autoQuit)
164 IsAutoQuit_ = autoQuit;
167 void SetQuitWait (
unsigned long wait)
174 template<
typename F,
typename... Args>
175 QFuture<std::result_of_t<F (WorkerType*, Args...)>> ScheduleImpl (F
f, Args&&... args)
177 const auto fWrapped = [
f,
this] (
auto... args)
mutable {
return std::invoke (
f, Worker_.get (), args...); };
181 void Initialize ()
override
183 Worker_ = Initializer_->Initialize ();
185 Initializer_.reset ();
188 void Cleanup ()
override