PDA

View Full Version : QTimer and QThread



TheKedge
14th September 2006, 11:37
Hello,
I've got QThread sub-classed with run() re-implemented thus:

void Logger::run()
{
QTimer* timer = new QTimer();
timer->setInterval(updateIntervalSeconds*1000);
connect(timer, SIGNAL(timeout()), this, SLOT(doJob()));
timer->start();

exec();
timer->stop();

delete timer;
return;
}
where doJob() is a func that contains stuff to be done. The doJob() func gets called as excpected but when ending the thread I get a crash that points to the timer->stop(). Commenting that out the crash points at the delete timer; commenting that out, the crash points to run()s end brace.

I get a Qt message QThread object destroyed while thread is still running, but I call the quit() func before deleting the object. what's going on?

thanks
K

TheKedge
14th September 2006, 11:44
Sorry, I think I have it.
in my destructor I call quit(), apparently, I need also to call wait() before letting the destructor finish.

thanks
K

Poter
20th September 2006, 16:40
Hello,
I think You can improve your run() function in the following way:


void Logger::run()
{
QTimer timer;
timer.setInterval(updateIntervalSeconds*1000);
connect(&timer, SIGNAL(timeout()), this, SLOT(doJob()));

timer.start();

exec();
}

I think it is better to create QTimer object on the stack. This object will be destroyed automatically when the run() function finishes. When You call exec() - evet loop is started at this point.

Br,
Poter

TheKedge
21st September 2006, 15:28
ok,
I've see that the doJob() function is executed in main (gui) thread. Have I set up my timer incorrectly?
By the way, I need the job executed every second or so, and I just wanted to use a timer instead of having a while loop with a sleep().

how do I get the timer firing so that doJob() runs in the new thread?

thanks
K

jacek
21st September 2006, 15:52
how do I get the timer firing so that doJob() runs in the new thread?
Try:

connect( &timer, SIGNAL( timeout() ), this, SLOT( doJob() ), Qt::DirectConnection );
or move doJob() to another class that you will instantiate in run(), since the Logger instance itself lives in the GUI thread.