PDA

View Full Version : Thread safe or not



raj_iv
19th January 2013, 21:01
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() {
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();
}

and in main.cpp file


int main(int argc, char *argv[])
{
QApplication app(argc, argv);

Worker* worker = new Worker();

worker->doStart();

worker->thread()->wait();

worker->deleteLater();

return app.exec();
}

wysota
19th January 2013, 22:28
No, it's not thread safe. No QObject based class is thread-safe and you are accessing QThread which is derived from QObject (and possibly your Worker class is also QObject derived). However your class is reentrant.