Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QThread event loop and infinite work loop

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?

like image 377
user14416 Avatar asked Jul 07 '13 18:07

user14416


3 Answers

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.

like image 123
Nikos C. Avatar answered Nov 14 '22 01:11

Nikos C.


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().

like image 31
Pavel Strakhov Avatar answered Nov 14 '22 00:11

Pavel Strakhov


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.

like image 1
Zlatomir Avatar answered Nov 14 '22 01:11

Zlatomir