Queue several QTimers calls to slots - c++

I'm using a library where I need to call a trigger function that starts some processing (starts a thread that does the job) and returns immediatly. Then when the processing is finished a signal is emitted.
This needs to be done periodically based on different parameters. Since other calls to the trigger function must not be done while processing I would need to queue them in some way. I thought about using a QEventLoop ("loop") but without luck so far.
Please look at this piece of code:
test::test()
{
connect(&timer, SIGNAL(timeout()), this, SLOT(timerSlot()));
connect(&timer2, SIGNAL(timeout()), this, SLOT(timer2Slot()));
connect(&library, SIGNAL(processingFinished()), &loop, SLOT(quit()));
timer.setInterval(2000);
timer.start();
timer2.setInterval(4000);
timer2.start();
}
void test::timerSlot()
{
loop.exec();
startProcessing(some_parameters);
}
void test::timer2Slot()
{
loop.exec();
startProcessing(some_other_parameters);
}
The issue is that when loop.exec() is called while processing I get the message:
QEventLoop::exec: instance xxxxxx has already called exec()
What would be the right way to do what I intend?
Thanks in advance.

One simple solution is to introduce a member variable, for example, bool m_isProcessing, start processing only if m_isProcess == false, then set it to true when you start processing and reset it to false when processing is complete. Since the slots for your test QObject execute on the GUI/main thread, you don't need to worry about synchronization between timer slots and the slot that will execute when processing is finished.
If you want to keep track of events that occur during processing, you can use the same method: introduce a member variable to the test class to track the information you need.

It seems that you are looking for Qt::QueuedConnection.
Qt::QueuedConnection 2 The slot is invoked when control returns to the event loop of the receiver's thread. The slot is executed in the receiver's thread.
Therefore, you could write something like this:
connect(&timer, SIGNAL(timeout()), SLOT(timerSlot()), Qt::QueuedConnection);
connect(&timer2, SIGNAL(timeout()), SLOT(timer2Slot()), Qt::QueuedConnection);
For details, you could look into the well-known mandelbrot example how this is done in there, although it is using worker threads:
Mandelbrot Example

Related

Executing two thread in parallel with one thread containing an event

I have two functions which has to be executed after specific interval of time. So I create two threads and each function is executed in separate threads. One of the function "checkForEvent()" has a Event which is waiting for an event to happen.
When the "checkForEvent()" function is waiting for an event the other function "checkServer()" is not being executed even though it is run in a separate thread.
dongleThread = new QThread(this);
checkDongle = new QTimer();
checkDongle->setInterval(DONGLE_CHECK_TIMER);
checkDongle->moveToThread(dongleThread);
connect(checkDongle, SIGNAL(timeout()), this, SLOT(checkForEvent()));
connect(dongleThread, SIGNAL(started()), checkDongle, SLOT(start()));
dongleThread->start();
serverThread = new QThread(this);
checkServer = new QTimer();
checkServer->setInterval(SERVER_CHECK_TIMER);
checkServer->moveToThread(serverThread);
connect(checkServer, SIGNAL(timeout()), this, SLOT(checkServer()));
connect(serverThread, SIGNAL(started()), checkServer, SLOT(start()));
serverThread->start();
checkForEvent() //This function is waiting for an Event
checkServer()
How can I execute both the functions in separate threads ?
Thank you!!
Your connect call uses the default connection type: Qt::AutoConnection. Here is what this means:
Qt::AutoConnection: If the receiver lives in the thread that emits the signal, Qt::DirectConnection is used. Otherwise, Qt::QueuedConnection is used. The connection type is determined when the signal is emitted.
Here your QTimer and this are in a different thread. It means Qt::QueuedConnection will be used.
Qt::QueuedConnection: The slot is invoked when control returns to the event loop of the receiver's thread. The slot is executed in the receiver's thread.
So your two slots are called in the thread of this. If one is blocking, the other one will never run.
One way of fixing the problem is having a worker object moved to its own thread. The worker object would call checkForEvent and emit a signal after the wait is over. This signal can be connected to checkServer in this. With this, you need only one thread. You can look at the documentation of QThread for more information about worker objects.

QTimer in worker thread

I have a Worker class which does some work in another thread, where it's placed using moveToThread(). Inside Worker::doWork() method I also create a QTimer which is supposed to emit progress updates, based on the estimated time the task will take.
Here's an example:
ThreadController::ThreadController()
{
Worker* worker = new Worker;
worker->moveToThread(&m_workerThread);
// ...
m_workerThread.start();
emit startWorker(params); // connected to Worker::doWork()
}
class Worker : public QObject
{
Q_OBJECT
public slots:
Worker::doWork(const QString& params)
{
QTimer* timer = new QTimer(this);
connect( timer, SIGNAL(timeout)), this, SLOT(updateProgress()) );
timer->start(estimateTaskLength() / 100);
// perform work...
}
}
Now this doesn't work as intended. The updateProgress() slot only starts being called AFTER the work has been completed.
When the timer expires, the timeout event is queued to the event queue of your worker QThread. However, your worker QThread is busy executing doWork(), so the event can't be processed. Once the thread completes the doWork, control returns the the QThread's event loop and the timeout event is executed.
The simplest approach to fixing this would be to manually invoke the event loop using QCoreApplication::processEvents() at certain intervals throughout the execution of doWork(). This will allow the QThread to execute the timeout event earlier.
Alternative, you can use a different thread to perform these estimations. If they are not too performance-intensive, you can even use the GUI/main thread. The GUI/main thread is expected to remain "responsive" to events (otherwise the application appears to hang) so it can process the timeout event in a timely manner.
This probably depends on the type of connection between Qtimer::timeout and this::updateProgress.
By default, its a Qt::AutoConnection, which means that the timeout signal will be queued until the receiving object is ready to handle it. I.e. after doWork is finished.
If you connect using
connect( timer, SIGNAL(timeout)), this, SLOT(updateProgress()), Qt::DirectConnection );
the timeout signal should be treated immediately. (Make sure to include necessary mutexes and stuff though, as this is a typical case where e.g. concurrent accesses may occur..)
( http://qt-project.org/doc/qt-4.8/qt.html#ConnectionType-enum )

Could this code potentially run into an infinite loop?

Is it possible for this Qt code to run into an infinite loop?
QNetworkAccessManager m;
QNetworkReply *reply = m.get(QNetworkRequest(QUrl("http://www.example.org/")));
QEventLoop loop;
QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
qDebug() << reply->readAll();
delete reply;
This is basically a "synchronous" way to display the contents of a webpage.
I have not observed any issues using it, but I considered the following scenario:
The finished signal of reply is emitted before the event loop is created and the signal-slot connection between finished and quit is made
No signal will be emitted from that point forward thus never triggering quit
loop.exec() will continually loop
Is it possible for that to occur, or am I not understanding something about how the Qt event loop works?
While Qt executes your own code (the code above, for example), it can't process new signals and call slots. Every signal was emitted while your method is executing will be processed later. If you want to force processing of signals in middle of your method, you can call QCoreApplication::processEvents to process signals in your current event loop or QEventLoop::exec to do it in another loop.
So this code is safe. If a signal comes too fast, it will wait in the event queue.
If you're emitting a signal and there are slots connected to this signal using Qt::DirectConnection, these slots will be executed immediately. But this doesn't match your case. Qt have to execute some internal code before the singal will be emitted. It can't execute this code while your method is executing. There are only one thread and only one call stack.
Note that when you're using Qt threads event loops' behaviour is more complicated.
Just before running loop.exec(), you could check reply->isFinished(). If it is, just don't execute the loop.

Process Signals & Slots Using a Thread

I need to be able make a request GET request, which requires the use of signals to process the replies, and return the reply back in a a processed form. I've structured the code as described in Threading Wihtout the Headache, but when I run the reply is never received or processed.
// Set-up request
QNetworkAccessManager* pConnection(new QNetworkAccessManager());
connect(pConnection,
SIGNAL(finished(QNetworkReply*)),
this,
SLOT(process(QNetworkReply*)));
QUrl url;
url.setUrl(HOST);
url.addQueryItem("P1", "Hi");
url.addQueryItem("P2", "Bob");
// Send request
QNetworkRequest request(url);
pConnection->get(request);
// Wait for reply
QThread* pResponce(new QThread(this));
connect(this,
SIGNAL(processingFinished()),
pResponce,
SLOT(quit()));
pConnection->moveToThread(pResponce);
pResponce->start();
pResponce->wait();
pConnection->deleteLater();
pResponce->deleteLater();
return this->processedReply;
Obviously I'm missing something, but what? It works when I'm not using the threads (and the deletes), so it's not the URL or server.
Only the main/gui thread receives signals if you don't set up an event loop in the other threads.
If no event loop is running, events won't be delivered to the object. For example, if you create a QTimer object in a thread but never call exec(), the QTimer will never emit its timeout() signal. Calling deleteLater() won't work either. (These restrictions apply to the main thread as well.)
Source: http://doc.qt.digia.com/4.6/threads-qobject.html
See QThread::exec(). That's why in the example you're linking the QThreadEx class is introduced, and used (not in your code snipplet, though!)...

QThread - Using a slot quit() to exit the thread

I want to inform an object when a thread has finished running. However, I cannot get the thread to exit properly. I have the following code:
Processor.cpp
thread = new QThread;
tw = new ThreadWorker;
connect(tw, SIGNAL(updateStatus(QString)), this, SLOT(statusUpdate(QString)));
tw->doSetup(thread, strDic);
tw->moveToThread(thread);
thread->start();
while(thread->isRunning())
{
}
qDebug() << "Thread Finished";
ThreadWorker.cpp
void ThreadWorker::doSetup(QThread *thread, const string &path)
{
_strPath = path;
connect(thread, SIGNAL(started()), this, SLOT(run()));
connect(this, SIGNAL(finished()), thread, SLOT(quit())); //tried terminate() also
}
void ThreadWorker::run()
{
DirectorySearch dicSearch;
vector<string> vecFileList = dicSearch.getFileList(_strPath);
emit updateStatus("Directory Fetched");
emit finished();
}
The quit() slot does not seem to stop the thread (QThread::isFinished never returns true). Can someone guide me in the right direction?
(Note: ThreadWorker does not inherit from QThread)
Assuming that Processor.cpp is running in your main thread, the while(thread->isRunning()) loop has your main thread completely tied up. This means that your application's event loop cannot do any processing so the signalupdateStatus() for example, will never get processed. As mentioned in the comments, since the QThread object is created by the main thread, its signals won't work either since they will also require the main event loop to be doing its thing. Besides, if you are waiting in your main thread for your worker thread to do something, why use a worker thread at all? :)
Try removing the while loop, add a slot workDone() (or whatever you want to call it) to Processor.cpp and connect that to your Threadworker's finished() signal.
I had the same problem and found the answer. Here is my question:
What is the use of QThread.wait() function?
To solve your problem, you don't need to run the QCoreApplication::instance()->processEvents() in your while loop, what you need to do is, instead of invoking the quit() which tries to send a signal to your creating thread's event loop (which is now blocked by the while loop), you have to call it directly.
So for your code, drop the line:
connect(this, SIGNAL(finished()), thread, SLOT(quit())); //tried terminate() also
And instead of:
emit finished();
Use:
this->thread()->quit();
Tada... problem solved. Lesson learned: don't try to exit a worker thread by the qt signal-slot mechanism from within it, because your signals do not end up where they are supposed to (your worker thread's event loop), but they end up in the creating thread instead. You never know what that thread is doing, and if its event loop is running or not, and this shouldn't be of business to your worker thread anyways... Instead, call the quit directly.
You can use Qt::DirectConnection:
connect(this, SIGNAL(finished()), thread, SLOT(quit()), Qt::DirectConnection);
This stops the thread.
Instead of doing your 'doSetup' function... before you moveToThread, setup connections between SINGALS on tw's parent and SLOTS in tw.
I would do 4 connections.
First is to the run method in ThreadWorker. Thats simple and self explainatory enough.
Second is from your finished signal to the third SIGNAL connection below. A SIGNAL that quits the thread
Third to a SIGNAL that should call the terminate() slot of the thread. This will effectively close the event loop setup when you connect to the run method (exec is auto called when you do a start()) and since your run method isn't a loop of some sort, will close the thread without issue.
Forth is from the thread's terminated() SIGNAL to a SLOT in tw's parent. This will show you when the thread is dead if you want to do something at that point.
You do the above connections (if you need to pass in the string, add a variable to the run method and corresponding SIGNAL connection and you'll have the data), move to thread, thread start, then do the SIGNAL attached to the run method. Let it do its thing. When its finished, it will do a finished signal that gets tied to another signal that gets tied to the threads terminated slot. This will kill the event loop and exit the thread, pushing a terminated signal out so you can then do something.