CuteHMI - CuteHMI (CuteHMI.2)
Worker.hpp
1 #ifndef H_EXTENSIONS_CUTEHMI_2_INCLUDE_CUTEHMI_WORKER_HPP
2 #define H_EXTENSIONS_CUTEHMI_2_INCLUDE_CUTEHMI_WORKER_HPP
3 
4 #include "internal/common.hpp"
5 
6 #include <QObject>
7 #include <QEvent>
8 #include <QMutex>
9 #include <QWaitCondition>
10 #include <QThread>
11 
12 #include <functional>
13 
14 namespace cutehmi {
15 
22 class CUTEHMI_API Worker:
23  public QObject
24 {
25  typedef QObject Parent;
26 
27  Q_OBJECT
28 
29  public:
34  Worker(std::function<void()> task = nullptr);
35 
41  Worker(QThread & thread);
42 
43  ~Worker() override;
44 
49  std::function<void()> task() const;
50 
55  void setTask(std::function<void()> task);
56 
63  void wait() const;
64 
72  bool isReady() const;
73 
80  bool isWorking() const;
81 
88  void employ(QThread & thread, bool start = true);
89 
96  void work();
97 
98  signals:
102  void ready();
103 
104  protected:
108  class WorkEvent:
109  public QEvent
110  {
111  public:
117  static Type RegisteredType() noexcept;
118 
119  public:
123  WorkEvent();
124  };
125 
132  virtual void job();
133 
134  bool event(QEvent * event) override;
135 
136  private:
137  enum class State {
138  UNEMPLOYED,
139  EMPLOYED,
140  WORKING,
141  READY
142  };
143 
144  struct Members
145  {
146  State state;
147  std::function<void()> task;
148  mutable QMutex stateMutex;
149  mutable QWaitCondition waitCondition;
150  mutable QMutex workMutex;
151 
152  Members(std::function<void()> p_task):
153  state(State::UNEMPLOYED),
154  task(p_task)
155  {
156  }
157  };
158 
159  MPtr<Members> m;
160 };
161 
162 }
163 
164 #endif
165 
166 //(c)C: Copyright © 2018-2020, Michał Policht <michal@policht.pl>. All rights reserved.
167 //(c)C: This file is a part of CuteHMI.
168 //(c)C: CuteHMI is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
169 //(c)C: CuteHMI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
170 //(c)C: You should have received a copy of the GNU Lesser General Public License along with CuteHMI. If not, see <https://www.gnu.org/licenses/>.
cutehmi::Worker
Worker.
Definition: Worker.hpp:22
QMutex
QThread
std::function
QObject
cutehmi
Definition: constants.hpp:6
cutehmi::Worker::WorkEvent
Work event.
Definition: Worker.hpp:108
QEvent
QWaitCondition