Last active
June 22, 2018 14:49
-
-
Save antonl/9aace0c35e5eb2edca9b to your computer and use it in GitHub Desktop.
Qt Threads and StateMachine
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <QObject> | |
#include <QState> | |
#include <QStateMachine> | |
#include <QThread> | |
#include <QApplication> | |
#include <QDebug> | |
#include <QTimer> | |
// Worker Object | |
class Worker : public QStateMachine | |
{ | |
public: | |
Worker() : time(new QTimer(this)) | |
{ | |
QState *s1 = new QState(); | |
this->addState(s1); | |
this->setInitialState(s1); | |
time->setInterval(250); | |
connect(s1, SIGNAL(entered()), time, SLOT(start())); | |
connect(time, &QTimer::timeout, this, &Worker::tick); | |
} | |
~Worker() = default; | |
public slots: | |
void tick() { | |
qDebug() << "Tick!"; | |
} | |
private: | |
QTimer *time; | |
}; | |
// Main controller | |
class A : public QStateMachine | |
{ | |
public: | |
A(QObject *parent = 0) : W(new Worker) { | |
W->moveToThread(&T); | |
connect(W, &QStateMachine::started, this, &A::inS1); | |
T.start(); | |
QState *s1 = new QState(); | |
this->addState(s1); | |
this->setInitialState(s1); | |
connect(s1, &QState::entered, W, &Worker::start); | |
connect(&T, &QThread::finished, W, &QObject::deleteLater); | |
qDebug() << "Started the thread"; | |
} | |
~A() { | |
T.quit(); | |
T.wait(); | |
} | |
public slots: | |
void inS1() { | |
qDebug() << "in S1\n"; | |
qDebug() << "Worker is runnning? " << W->isRunning(); | |
} | |
public: | |
QThread T; | |
Worker *W; | |
}; | |
int main(int argc, char*argv[]) { | |
QApplication app(argc, argv); | |
A test; | |
test.start(); | |
qDebug() << "Is running? " << test.isRunning(); | |
qDebug() << test.thread() << " " << test.W->thread(); | |
qDebug() << "Thread is running? " << test.thread()->isRunning(); | |
qDebug() << "T is running? " << test.W->isRunning(); | |
return app.exec(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment