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  void setTask(std::function<void()> task);
50 
57  virtual void job();
58 
65  void wait() const;
66 
74  bool isReady() const;
75 
82  bool isWorking() const;
83 
90  void employ(QThread & thread, bool start = true);
91 
98  void work();
99 
100  signals:
104  void ready();
105 
106  protected:
110  class WorkEvent:
111  public QEvent
112  {
113  public:
119  static Type RegisteredType() noexcept;
120 
121  public:
125  WorkEvent();
126  };
127 
128  bool event(QEvent * event) override;
129 
130  private:
131  enum class State {
132  UNEMPLOYED,
133  EMPLOYED,
134  WORKING,
135  READY
136  };
137 
138  struct Members
139  {
140  State state;
141  std::function<void()> task;
142  mutable QMutex stateMutex;
143  mutable QWaitCondition waitCondition;
144  mutable QMutex workMutex;
145 
146  Members(std::function<void()> p_task):
147  state(State::UNEMPLOYED),
148  task(p_task)
149  {
150  }
151  };
152 
153  MPtr<Members> m;
154 };
155 
156 }
157 
158 #endif
159 
160 //(c)C: Copyright © 2018-2020, Michał Policht <michal@policht.pl>. All rights reserved.
161 //(c)C: This file is a part of CuteHMI.
162 //(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.
163 //(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.
164 //(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:110
QEvent
QWaitCondition