[SOLVED]- QThread - QEventLoop vs Sleep
-
I have a Thread starting from my QMainWindow that has a busy loop (execute until MainWindow ask him to close)
So far I am running this loop this way :@ /// Main Loop
while (antThreadRunning) {
QThread::msleep(150);
}@I was wondering if a QEventLoop would be more efficient
For example:@ /// Main Loop, done in .exec of QEventLoop
QEventLoop loop;
QObject::connect(thread, SIGNAL(antThreadRunningFinish()), &loop, SLOT(quit()) );
loop.exec();@By calling loop.exec, what is actually happening? is it an infinite loop that use lot of CPU? I would like to find the faster/better approach between the two, thank you!
-
QEvenLoop is more efficient then busy loop, it does not eat CPU like busy loop, and it allows the thread to process the signals and events.
If you need to wait for some predefined time then you can use something like this
@
QEventLoop loop;
QTimer timer;
QObject::connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
int runTime = seconds * 1000;
timer.start(runTime);
loop.exec();
@ -
Thanks for the info andreyc,
I'll replace all my busy loop with QEventLoop, I discover new awesome things in Qt every day!
@ /// Loop until channel closed or maximum of 25sec
QEventLoop loop;
QTimer timer;
timer.setSingleShot(true); // single serving timer...
timer.start(25 * 1000); // 25secQObject::connect(this, SIGNAL(signal_allChannelClosed()), &loop, SLOT(quit()) ); QObject::connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit())); loop.exec(); qDebug() << "loop done!";@
-
[quote author="maximus" date="1406208599"]
[...]
I'll replace all my busy loop with QEventLoop
[...]
[/quote]Beware though that "nested event loops can have unexpected and undesired side effects.":http://delta.affinix.com/2006/10/23/nested-eventloops/
-
Thanks for the heads up!
It's all good the code in executed during the EventLoop is all code I control and no nested event-looping is done ;)