QThread - Using Timer instead of forever loop?
-
I want to have a Thread that will process an event loop, sending data back to the main Thread at a really fast pace. I still want the Thread to be responsible to signals so I don't want to use a busy loop, because in a busy loop the slots of the Tread would not get called.
I'm just wondering if using a QTimer inside a Thread is a good solution? Will it let my Thread process signal/slot during the time it's free?Here is a code sample:
Main:
thread = new QThread; compuTrainer = new CompuTrainer; compuTrainer->moveToThread(thread); connect(compuTrainer, SIGNAL(dataChanged(int)), this, SLOT(dataChanged(int)) );
CompuTrainer.cpp
timerUpdateData = new QTimer(this); connect(timerUpdateData, SIGNAL(timeout()), this, SLOT(updateData()) ); timerUpdateData->start(150); void CompuTrainer::updateData() { emit dataChanged(someDataHere); }
Edit: Coded fully and seems to be working, just want to make sure using QTimer inside the Thread is okay.. Thanks
-
@maximus
I would think the different sleep methods are for that. -
Hi,
Using
QTimer
inside a Thread is IMO the best solution to achieve your goal. -
Thanks! [Solved]
Just wondering why I could not google this solution, found many subclass QThread solution that seems really complicated compared to this one.
-
Hi,
subclassing thread was probably the first solution used in the past but now the one with
moveToThread()
is the best one and also the simpler to manage.BTW, you can refer to this to figure out what is the best solution depending to what do you need
-
@maximus Hi! Have a look at this blog post: https://mayaposch.wordpress.com/2011/11/01/how-to-really-truly-use-qthreads-the-full-explanation/
8/8