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
-
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. -
@koahnig
While the Thread is sleeping, can it still receive signals?
Also, I didn't subclass QThread, i'm just using a vanilla Thread so I can't use sleep directly. -
-
Thanks! [Solved]
Just wondering why I could not google this solution, found many subclass QThread solution that seems really complicated compared to this one.
@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/