[Qt-interest] Long Calculations, QThread Event Loop, Signals & Slots
Michael Jackson
mike.jackson at bluequartz.net
Mon Jan 17 20:20:33 CET 2011
I read the recent posts with regard to the "proper way" of using QThreads,
subclassing and all of that. And I understand what the Qt engineers are
telling us. Thus, I went back to some current code to change my class to
inherit from QObject instead of QThread. I made the adjustments in my Gui
MainWindow code to create a QThread, create my calculation object, move the
calculation object to the newly created QThread and then start the thread.
There is still a problem where my calculation object is NOT getting a signal
until the long running calculation object is done, at least with
QueuedConnections. So here is my general setup:
class LongCalc {
void compute() {
// Stuff that takes 10 minutes to run
}
};
Class MyMainWindow : public QMainWindow ....
{
void on_GotBtn_clicked()
{
t = new Qthread();
calc = new LongCalc();
calc->moveToThread(t);
// When the thread starts its event loop, start the LongCalc going
connect(t, SIGNAL(started()), calc, SLOT(compute()));
//When the LongCalc ends then tell the QThread to stop its event loop
connect(calc, SIGNAL(finished() ), t, SLOT(quit()) );
// When the QThread finishes, tell this object that it has finished.
connect(t, SIGNAL(finished()), this, SLOT( rec_ThreadFinished() ) );
connect(this, SIGNAL(sig_CancelWorker() ),
calc, SLOT (on_CancelWorker()) );
t->start();
}
private:
QThread* t;
LongCalc* calc;
};
If the "sig_CancelWorker()" signal gets emitted then the slot isn't called
until AFTER the "compute()" method has finished. Thinking through what is
likely going on makes sense (I think). QThread.run() is called which starts
the event loop for that thread. The QThread then sends out the "started()"
signal which the LongCalc has hooked up to a slot (compute()) so the
"Compute()" method now runs which effectively blocks the event loop from
running? Is that correct? I thought I knew what I was supposed to do but now
it seems like a need yet a third thread to actually run the long computation
while I have an intermediate thread that has an event loop that is running
to deliver the messages to the third thread?
My mind wants to create some sort of "Queue" system like a
Producer-Consumer" so that the slot can return right away and then ask a the
other sleeping thread to wake up and calculate. This just smells like I am
missing something obvious with Qt and Threads.
More thoughts and clarifications would just be wonderful.
Thanks
--
Mike Jackson www.bluequartz.net
More information about the Qt-interest-old
mailing list