1 | // %pacpus:license{
|
---|
2 | // This file is part of the PACPUS framework distributed under the
|
---|
3 | // CECILL-C License, Version 1.0.
|
---|
4 | // %pacpus:license}
|
---|
5 |
|
---|
6 | #include <Pacpus/PacpusTools/AsyncWorkerBase.h>
|
---|
7 |
|
---|
8 | #include <Pacpus/kernel/Log.h>
|
---|
9 |
|
---|
10 | #include <QThread>
|
---|
11 |
|
---|
12 | using namespace pacpus;
|
---|
13 | DECLARE_STATIC_LOGGER("pacpus.core.workers");
|
---|
14 |
|
---|
15 | AsyncWorkerBase::AsyncWorkerBase()
|
---|
16 | : active_(false)
|
---|
17 | , stopping_(false)
|
---|
18 | {
|
---|
19 | }
|
---|
20 |
|
---|
21 | AsyncWorkerBase::~AsyncWorkerBase()
|
---|
22 | {
|
---|
23 | }
|
---|
24 |
|
---|
25 | void
|
---|
26 | AsyncWorkerBase::start()
|
---|
27 | {
|
---|
28 | if (!isActive())
|
---|
29 | {
|
---|
30 | QThread* theThread = new QThread;
|
---|
31 |
|
---|
32 | // Executes the setup() method as soon as theThread is started
|
---|
33 | connect(theThread, SIGNAL(started()), SLOT(doSetup()));
|
---|
34 |
|
---|
35 | // Executes the finish() method as soon as theThread
|
---|
36 |
|
---|
37 | // Allows stopping requests to be handled withing the worker thread instead
|
---|
38 | // of the thread that made the stop() call.
|
---|
39 | connect(this, SIGNAL(stopped()), this, SLOT(doFinish()));
|
---|
40 |
|
---|
41 | // Guarantees theThread is terminated and deleted once the worker has
|
---|
42 | // stopped and is destroyed
|
---|
43 | connect(this, SIGNAL(finished()), theThread, SLOT(quit()));
|
---|
44 | connect(theThread, SIGNAL(finished()), theThread, SLOT(deleteLater()));
|
---|
45 |
|
---|
46 | active_ = true;
|
---|
47 | this->moveToThread(theThread);
|
---|
48 | theThread->start();
|
---|
49 | }
|
---|
50 | }
|
---|
51 |
|
---|
52 | void
|
---|
53 | AsyncWorkerBase::stop(bool autoDelete)
|
---|
54 | {
|
---|
55 | if (isActive())
|
---|
56 | {
|
---|
57 | if (autoDelete)
|
---|
58 | {
|
---|
59 | // Guarantees deletion of this once all pending signals have been handled
|
---|
60 | connect(this, SIGNAL(finished()), this, SLOT(deleteLater()));
|
---|
61 | }
|
---|
62 | stopping_ = true;
|
---|
63 | emit stopped();
|
---|
64 | }
|
---|
65 | else
|
---|
66 | {
|
---|
67 | if (autoDelete)
|
---|
68 | delete this;
|
---|
69 | }
|
---|
70 | }
|
---|
71 |
|
---|
72 | void AsyncWorkerBase::finish()
|
---|
73 | {
|
---|
74 | if (isActive())
|
---|
75 | {
|
---|
76 | cleanup();
|
---|
77 | emit finished();
|
---|
78 | active_ = false;
|
---|
79 | }
|
---|
80 | }
|
---|
81 |
|
---|
82 | void AsyncWorkerBase::setup()
|
---|
83 | {
|
---|
84 | }
|
---|
85 |
|
---|
86 | void AsyncWorkerBase::process()
|
---|
87 | {
|
---|
88 | }
|
---|
89 |
|
---|
90 | void AsyncWorkerBase::cleanup()
|
---|
91 | {
|
---|
92 | }
|
---|
93 |
|
---|
94 | void AsyncWorkerBase::doSetup()
|
---|
95 | {
|
---|
96 | setup();
|
---|
97 | process();
|
---|
98 | }
|
---|
99 |
|
---|
100 | void AsyncWorkerBase::doFinish()
|
---|
101 | {
|
---|
102 | finish();
|
---|
103 | }
|
---|