I need to make infinite loop of work in a thread. In this article the author writes that
>you should never ever block the event loop
because it will block the signal-slot concept. How can I use event loop plus infinite loop in QThread?
QThread is the thread "controller". Its event loop doesn't block just because your QObject executes an infinite loop. Unless of course you're implementing that infinite loop in a QThread subclass.
In your case, you don't have to do that. Instead, just implement your infinite loop in a QObject subclass and then move that QObject to a thread with QObject::moveToThread(). That way your infinite loop doesn't block the QThread's event loop.
And, as always: the canonical article on how to really use QThread.
A loop always can be replaced with a function that is called multiple times (although it's not always convenient). Create a slot and connect a QTimer to it. Let the function do the iteration of work.
timer = new QTimer();
connect(timer, SIGNAL(timeout()), this, SLOT(iteration()));
timer->start(50);
void MyClass::iteration() {
if (!timer->isActive()) { return; }
//do something
}
If you want to stop the loop, call timer->stop().
A call to QCoreApplication::processEvents should work, but maybe a better solution is to use a QThreadPool instead of forcing a thread to keep running.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With