Look at following code n pls let me know whether my Worker class is thread safe or not. I have a Worker class cpp as follows: m_str is Qstring member variable in Worker class n m_thread is QThread in same class.
Worker::Worker() {
moveToThread(m_thread);
connect(m_thread, SIGNAL(started()), this, SLOT(process()));
connect(m_thread, SIGNAL(finished()), this, SLOT(quit()));
connect(m_thread, SIGNAL(finished()), m_thread, SLOT(deleteLater()));
}
Worker::~Worker() {
}
void Worker::doStart()
{
.... // not touching m_str
m_thread->start(); // this always last stmt. in this function
}
void Worker::process() {
m_thread->quit();
}
Worker::Worker() {
m_thread = new QThread;
moveToThread(m_thread);
connect(m_thread, SIGNAL(started()), this, SLOT(process()));
connect(m_thread, SIGNAL(finished()), this, SLOT(quit()));
connect(m_thread, SIGNAL(finished()), m_thread, SLOT(deleteLater()));
}
Worker::~Worker() {
}
void Worker::doStart()
{
.... // not touching m_str
m_thread->start(); // this always last stmt. in this function
}
void Worker::process() {
m_str = QString("Hello!");
m_thread->quit();
}
To copy to clipboard, switch view to plain text mode
and in main.cpp file
int main(int argc, char *argv[])
{
Worker* worker = new Worker();
worker->doStart();
worker->thread()->wait();
worker->deleteLater();
return app.exec();
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
Worker* worker = new Worker();
worker->doStart();
worker->thread()->wait();
worker->deleteLater();
return app.exec();
}
To copy to clipboard, switch view to plain text mode
Bookmarks