Asynchronous function calls in Qt - c++

I'm pretty new to Qt and programming and are facing a problem I can't find a solution for.
I want to read some information from an online XML file and send it to my main program.
To do so, I created a class XMLParser and added the following to the constructor:
XMLParser::XMLParser(QString searchstring)
{
QNetworkAccessManager *manager2 = new QNetworkAccessManager(this);
reply = manager2->get(QNetworkRequest(QUrl("http://www.boardgamegeek.com/xmlapi/search?search="+searchstring)));
XMLParser::connect(reply, SIGNAL(finished()),
this, SLOT(fileIsReady()) );
}
and fileIsReady fills a QMap and stores it as a private class member.
In my second class, I call
XMLParser *xmlpars = new XMLParser(input_gamename->text());
QMap<QString, int> searchResults = xmlpars->getSearchList();
and getSearchList is a simple getter function.
The problem is, that getSearchList is executed before fileIsReady finished reading the XML file and returns an empty map.
From what I understand, the constructor should not be finished until fileIsReady() finished its work. And thus, getSearchList() shouldn't be called early.
My two questions:
Why does my programm progresses while the function didn't finish reading.
How can I make the second call "getSearchList" wait?
Thanks a lot in advance!

First, you need to understand the fundamental concept of signals and slots.
After you make a connection, the slot will get called every time the signal is emitted.
The connect() functions returns after connecting the signal to the slot. It doesn't wait for the signal to be emitted.
In your XMLParser constructor, your connect() function registers this: "When the finished() signal is emitted, run the fileIsReady() function".
Now, to answer your questions.
Why does my programm progresses while the function didn't finish reading.
Because in your constructor code, you asked the constructor to finish after you connect the signal to the slot. You did not ask it to wait for the download to finish.
And then, you call getSearchList() without waiting for the finished() signal. So, getSearchList() gets called before fileIsReady().
How can I make the second call "getSearchList" wait?
Like MrEricSir said, you shouldn't ask it to wait! (Think about it: What happens if you lose internet connection and can't finish downloading the file? The answer is, your program will freeze because it will wait forever. That's bad.)
Don't call getSearchList() immediately after constructing XMLParser. Instead, make XMLParser emit a "finishedParsing()" signal when it finishes parsing the XML file. Then, make another signal-slot connection: Connect the finishedParsing() signal to a slot that calls getSearchList().

So, I found a solution using QEventLoop. But as far as I read, this isn't recommendend.
Are there any other solutions? And why is using QEventLoop bad habit (That's what I read from other answers here StackOverflow).
XMLParser::XMLParser(QString searchstring)
{
QNetworkAccessManager *manager2 = new QNetworkAccessManager(this);
reply = manager2->get(QNetworkRequest(QUrl("http://www.boardgamegeek.com/xmlapi/search?search="+searchstring)));
QEventLoop loop;
XMLParser::connect(reply, SIGNAL(finished()),
this, SLOT(fileIsReady()) );
XMLParser::connect(this, SIGNAL(finishedReading()),
&loop, SLOT(quit()));
loop.exec();
}

How can I make the second call getSearchList wait?
You don't! Instead, just move any code that expect the XML file to be downloaded into the fileIsReady() slot that you've already defined. That way your program won't lock up while it's waiting for the download to complete (which is the entire point of asynchronous programming.)

Related

How to monitor QThread

I am working on Qt application. There I would like to have worker thread doing some activities in background and I would like main thread to control it, restarting worker thread if it dies for some reason.
I have seen finished() signal emitted by the thread so I guess I could connect slot to it.
Is that the recommended way? If not, how could I achieve that?
If I use finished() signal how can I know difference between normal termination and error?
Thanks and regards
If you want to know whether you had an error or you had the process finished, simply create two signals, not one, and two slots, not one.
In the Qt documentation you have an example there, with a connection to handle the result:
connect(workerThread, &WorkerThread::resultReady, this, &MyObject::handleResults);
you're here connecting the signal resultReady with whatever method that handles the result. You create another one exactly like this, but with an error signal, and an error handler.
connect(workerThread, &WorkerThread::errorThrown, this, &MyObject::handleErrors);
Of course, another option is to simply pass a parameter with your signals/slots. It's a function call, and if you put some enum with that for the status or some int, that'll do.

Simple network timeout in Qt(c++)

I'm writing a simple network file transfer application in Qt, and I'm struggling to implement a timeout.
Basically, what I want is the following,
while(!AcknowledgeReceived)
{
if(timeout)
{
break;
}
}
Currently, timeout is changed by a Qtimer, but once the loop starts execution, it never leaves. (The Slot QTimer emits to doesn't get executed.)
I gather that this has something to do with threads, but I'm way to new at this to implement it correctly.
So my question to you is, how do I go about ensuring that the method flipping timeout is executed, or how do I get the same results with another method?
When you're looping like that, the Qt main event loop will not run, as it's in the call to your function.
You either need to redesign your application to only use slots and signals, so you don't need the loop. Or you have to process the Qt event yourself.
For example
QNetworkAccessManager netman;
QNetworkRequest request{url};
QNetworkReply* reply = netman.post(request, data);
while (!reply->isFinished())
{
QThread::msleep(1);
qApp->processEvents();
}

pthread 2 signals and slots wrapper mit QEventLoop

problem
i'm currently putting FUSE together with qt5. there is no bridge between Qt and FUSE yet, both the FUSE main thread (which is spawning the other working FUSE threads) and the QCoreApplication are simply running side by side.
but i want to be able to send and receive data between a QObject based object and the pthread's Read(..) function shown in [0] using Qt's SIGNALS and SLOTS.
question
now i want to alter the Read(..) function from [0] to retrieve data using Qt's SIGNALS and SLOTS from a QObject based class. sending a signal from a pthread works but without an explicit QEventLoop i can't receive the reply. therefore i was looking at the code from [1] which is excellent in design but i didn't get it working yet.
pseudo code (taken from [1]):
QNetworkAccessManager qnam;
QNetworkReply *reply = qnam.get(QNetworkRequest(QUrl(...)));
QEventLoop loop;
QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
/* reply has finished, use it */
looks interesting, all i would need is a QObject deriving class similar to the QNetworkReply which would handle the request.
when i was playing with that code i had the problem that my implementation of QNetworkReply wouldn't wait for loop.exec() to be running and then the finished() SIGNAL wouldn't be received by the loop.
but isn't there something easier than to spawn a QEventLoop?
NOTE: the QNetworkReply and QNetworkAccessManager in the example from [1] is spawned inside the pthread, i however, need to be able to communicate with the QCoreApplication's even queue using SIGNALS and SLOTS since the object with the data in it comes from a different QThread (in this either the QCoreApplication or a special QThread).
using a Qt::QueuedConnection
i've also found [2] and maybe:
connect(src, SIGNAL(signal-signature), dest, SLOT(slot-signature), Qt::QueuedConnection);
is all i want but i doubt that.
links
[0] https://github.com/qknight/qt-fuse-example/blob/4d92a74fad22fd559588e58be67f766174c7efb8/qt-fuse/examplefs.cc#L74
[1] http://qt-project.org/wiki/ThreadsEventsQObjects#7494f2b4836907fc1c09311e3a0305e6
[2] emit Qt signal from non Qt Thread or ouside Qt main event loop with at 4.5
What you're likely facing is that QNetworkAccessManager internally uses threads to process http requests. That's why it "doesn't wait" for you. There's a rather simple modification needed to fix it:
QNetworkAccessManager qnam;
QEventLoop loop;
QNetworkReply *reply = qnam.get(QNetworkRequest(QUrl(...)));
QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
if (!reply->isFinished()) loop.exec();
Things to note when using QObjects in Multiple Threads
When the object that is the source of a signal lives (is instantiated in) a thread different than the thread of the object with slots, the connection will be of the QueuedConnection type automatically.
The real issue is: Each QObject has a thread affinity. The default affinity is the thread where the object was instantiated. You're not supposed to use such objects directly from other threads.
What you're likely doing is instantiating the sender and receiver objects in the same thread, but then emitting the signal from another thread. This is a source of potential errors error and leads to undefined behavior if the user of such an object is forcing a non-automatic direct connection.
Whenever you do emit object->signal(...), the following invariant should hold:
Q_ASSERT(QThread::currentThread() == object->thread());
Feel free to add those invariant checks in front of every emit() that you explicitly perform.
If the assertion fails, you need to use QObject::moveToThread to move the object to the thread where you want to fire its signals. You can get a QThread for a given pthread by calling QThread::currentThread() from the code that runs in the pthread. An instance of a QThread will be created automagically for you :)
Yes, you want the Qt::QueuedConnection method. But also ensure that you are using the multithreading Qt library. IIRC it is a build-time option.
See also: Qt documentation

Qt Thread object only sending signal as Qt:DirectConnection - why?

I have a class derived from QThread: class MyClass : public QThread
This class is connected with a slot of another object. Originally this was connected as Qt::AutoConnection. But then - as soon as the thread is started (MyClass::run()) - the signal is no longer "reaching the slot" (why?).
// connected before myObject->run()
s = QObject::connect(
_myObject, SIGNAL(signalLogMessage(const QString&, QtMsgType)),
this, SLOT(slotLogMessage(const QString&, QtMsgType)), Qt::DirectConnection);
My first idea was that I need to force Qt::QueuedConnection (this / _myObject will be cross threaded). In this case it does not work at all. Only Qt::DirectConnection works. After the thread is started, IMHO Qt::QueuedConnection is the correct choice (cross thread).
Any idea what is going wrong? The connection itself seems to be correct, otherwise it was not working at (mean even not with Qt::DirectConnection).
Edit 1: -- As of hyde's answer / Nikos' comment
As of right now I think hyde's answer / Nikos' comment are pointing out the root cause. My QThread is running it's own message loop for another application. This is the reason why it is running in its own thread and is basically an infinite loop
run() {
// exec(); // while not reached
while (_runMessageLoop && ...) {
hr = CallDispatch(.....);
if (hr== 0) QThread::msleep(100);
// QCoreApplication::processEvents();
}
}
Guess due to this infinite loop the Qt message loop is not running and no signal / slots are processed (is this correct?) When forcing Qt::DirectConnection the methods are called directly with no Qt message loop required, this might be the reason why this is the only connection type working.
The question is now, how can I combine the Qt and my own message loop (if this is feasible)? Cannot call exec() before the loop (because then it is in the Qt loop), and just the QCoreApplication::processEvents(); in "my loop" is still not working.
=> see new Question here: How to combine own message loop and Qt event loop?
Hard to say without seeing all the code, but it may be because of this:
QThread object itself is not the thread, it's the thread controller. Most importantly, QThread object's thread affinity should not be the thread it controls. If your thread runs Qt event loop, then it's best to avoid subclassing QThread. Instead, have your logic (inter-thread slots etc) in another QObject, which you move to the thread you created with moveToThread after creating it. Only real reason to subclass QThread is to override run() method with one which does not call exec().
Related reading:
https://www.qt.io/blog/2010/06/17/youre-doing-it-wrong
Addition:
If you override QThread::run(), you have to call QThread::exec() there or event loop won't be running and no non-direct signal gets delivered to any QObject with that thread affinity. If you want to have your own event loop, that is possible, you just have to call QCoreApplication::processEvents() to process Qt events.

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.