Hi,
I have a quite simple problem that is driving me crazy.
I have some operations that are performed on a thread. I have an object that's doing the heavy job, and I'm moving it to a thread, as suggested in http://labs.qt.nokia.com/2010/06/17/...oing-it-wrong/
The object is created the following way
MainDialog
::MainDialog(QWidget *parent, Qt
::WindowFlags f
){
/* ... */
myObject = new MyObject;
myObject->moveToThread(myThread);
connect( myThread, SIGNAL( started() ),
myObject, SLOT( start() ) );
connect( myObject, SIGNAL( finished() ),
myThread, SLOT( quit() ) );
}
MainDialog::MainDialog(QWidget *parent, Qt::WindowFlags f)
: QDialog(parent, f)
{
/* ... */
myThread = new QThread(this);
myObject = new MyObject;
myObject->moveToThread(myThread);
connect( myThread, SIGNAL( started() ),
myObject, SLOT( start() ) );
connect( myObject, SIGNAL( finished() ),
myThread, SLOT( quit() ) );
}
To copy to clipboard, switch view to plain text mode
Ideally when I start myThread the start() slot should be called on myObject and when myObject emits the finished() signal my thread should quit.
The implementation of MyObject is as simple as this
void MyObject::start()
{
QTimer::singleShot( 0,
this,
SLOT(doOperation
()) );
}
void MyObject::doOperation()
{
if( stopped() )
{
emit finished();
return;
}
/* ... */
QTimer::singleShot(1000,
this,
SLOT(doOperation
()));
}
void MyObject::stop()
{
_stopped = true;
}
bool MyObject::stopped() const
{
return _stopped;
}
void MyObject::start()
{
QTimer::singleShot( 0, this, SLOT(doOperation()) );
}
void MyObject::doOperation()
{
if( stopped() )
{
emit finished();
return;
}
/* ... */
QTimer::singleShot(1000, this, SLOT(doOperation()));
}
void MyObject::stop()
{
QMutexLocker ml(&_mutex);
_stopped = true;
}
bool MyObject::stopped() const
{
QMutexLocker ml(&_mutex);
return _stopped;
}
To copy to clipboard, switch view to plain text mode
Essentially an operation is performed periodically till the operation is not stopped through the stop() method.
On the main application I start the thread
void MainDialog::onStartClicked()
{
myThread->start();
}
void MainDialog::onStartClicked()
{
myThread->start();
}
To copy to clipboard, switch view to plain text mode
and myObject starts working as expected.
The problem happens when I stop the object flow calling the stop function
void MainDialog::onStopClicked()
{
myObject->stop();
myThread->wait();
/* ... */
}
void MainDialog::onStopClicked()
{
myObject->stop();
myThread->wait();
/* ... */
}
To copy to clipboard, switch view to plain text mode
the wait() on myThread freezes my application and the quit() slot on myThread is never called.
I really do not understand why, since the thread has its own event loop.
I'm using Qt 4.7.3 on Windows.
Thanks in advance for your help.
Bookmarks