How to setup signal/slot connection between thread and child thread? - c++

I have a class ParentThread deriving from QThread with the following run() method that roughly looks as follows:
void ParentThread::run()
{
QThread *childThread = new QThread;
QObject::connect(childThread, SIGNAL(finished()), this, SLOT(onChildThreadFinished());
QObject::connect(childThread, SIGNAL(finished()), childThread, SLOT(deleteLater());
childThread->start();
exec();
}
The slot onChildThreadFinished() is defined on ParentThread, and should run in the context of ParentThread. However, using the code above, onChildThreadFinished only gets called in case the signal/slot connection is a Qt::DirectConnection, but then runs in the context of the child thread. In case the signal/slot connection is defined as a Qt::QueuedConnection, the slot never gets called. I am using Qt 4.8.5. Any idea what the issue is here?

You state that The slot onChildThreadFinished() is defined on ParentThread, and should run in the context of ParentThread. This assumption is wrong. This is one of the reasons why subclassing QThread is discouraged.
If you want to use slots in your threads, subclassing QThread is not what you want to do. Use worker-object method instead. Subclass QObject and call QObject::moveToThread to move your object to a new thread.
Here is what Qt docs say about this:
It is important to remember that a QThread instance lives in the old thread that instantiated it, not in the new thread that calls run(). This means that all of QThread's queued slots will execute in the old thread. Thus, a developer who wishes to invoke slots in the new thread must use the worker-object approach; new slots should not be implemented directly into a subclassed QThread.

Related

Invoking a function on a QThread that is already running

I have seen a lot of examples on the internet (and the Qt documentation) where to use QThread, a subclass of the class is made and then a worker object is moved to that thread. Then essentially the QThread::started() signal is connected to some slot of the worker class object to run a certain function.
Now I would like to do the same in my project, the difference being I would like to move my worker class to a thread that is already running and then call some function on that thread. To achieve this I came up with a slight hack like in the code below, where I use the QTimer class to invoke a public slot in my worker class.
QThread myThread;
myThread.setObjectName("myThread");
myThread.start();
Worker worker;
worker.moveToThread(&myThread);
QTimer::singleShot(0, &worker, [&worker](){
worker.doStuff(5);
});
Is there a more idiomatic way to achieve the same thing?
If "doStuff" is a slot then you can use QMetaObject::invokeMethod:
QMetaObject::invokeMethod(&worker, "doStuff", Qt::QueuedConnection, Q_ARG(int, 5));

What is the proper way to execute some lambda func periodically in background thread with Qt?

I have to execute some heavy code in background thread by timeout. And I do not want to subclass QThread for every such workers. Is this a proper way?
/* inside QObject subclass */
auto thread = new QThread(this);
auto timer = new QTimer(nullptr);
timer->moveToThread(thread);
timer->setInterval(1000);
connect(timer, &QTimer::timeout, [](){
/* do lambda work */
});
connect(thread, SIGNAL(started()), timer, SLOT(start()));
connect(thread, &QThread::destroyed, timer, &QTimer::deleteLater);
thread->start();
Initially the code presented looks ok. However, it depends on what you plan to do in the lambda function and what objects you're going to use and where they reside.
Your lambda function doesn't capture any variables. If this is intended, then it should be fine. However, if you're planning on using objects which have already been instantiated on the main thread, you'll have to think carefully about their thread affinity (which thread they're running on) when you try to use them in the lambda function.
Personally, I'd create a separate object, derived from QObject, which creates the QTimer and lambda function, then move that object to the new thread. Communication between this object and those on the main thread is performed via signal and slots.

Is this the correct way to use a QThread?

I am looking at some github projects, where one of them did the UDPlink in the following way,
first it subclass QThread to create a class UDPLink:public QThread
and its constructor and deconstructor is like:
UDPLink::UDPLink(UDPConfiguration* config)
: _socket(NULL)
, _connectState(false)
{
Q_ASSERT(config != NULL);
_config = config;
_config->setLink(this);
// We're doing it wrong - because the Qt folks got the API wrong:
// http://blog.qt.digia.com/blog/2010/06/17/youre-doing-it-wrong/
moveToThread(this);
// Set unique ID and add link to the list of links
_id = getNextLinkId();
qDebug() << "UDP Created " << _config->name();
}
UDPLink::~UDPLink()
{
// Disconnect link from configuration
_config->setLink(NULL);
_disconnect();
// Tell the thread to exit
quit();
// Wait for it to exit
wait();
this->deleteLater();
}
Though the code did compile and work, but I wonder whether this way of using a QThread would be correct?
The Qt docs for QThread describe the two ways threading can be done with QThread. Sub-classing QThread was the only way to use QThread initially. To use QThread in this manner, override the run method, which is the QThread method that runs on a new thread. QThread should be thought of as a thread manager, not an object that runs on a separate thread itself. From the docs:
It is important to remember that a QThread instance lives in the old
thread that instantiated it, not in the new thread that calls run().
This means that all of QThread's queued slots will execute in the old
thread. Thus, a developer who wishes to invoke slots in the new thread
must use the worker-object approach; new slots should not be
implemented directly into a subclassed QThread.
When subclassing QThread, keep in mind that the constructor executes
in the old thread while run() executes in the new thread. If a member
variable is accessed from both functions, then the variable is
accessed from two different threads. Check that it is safe to do so.
QThread documentation page
It's because QThread is a thread manager class that a solution for moving objects to threads was created. The comment in the code you provided makes a statement about this change, since that article states that moveToThread(this) isn't a good practice.
Creating an object and moving it to a thread and sub-classing QThread are both valid approaches to threading with Qt, as the documentation now states clearly. There is a benefit to using the worker-object approach, if you desire to use signal/slot connections across thread boundaries: a worker object will have its slots available on the thread it is moved to.
As Qt developer recommended, Code you mentioned is not correct way to use QThread.
Recommended way is suggested here.
Sample code from Post.
Producer producer;
Consumer consumer;
producer.connect(&consumer, SIGNAL(consumed()), SLOT(produce()));
consumer.connect(&producer, SIGNAL(produced(QByteArray *)), SLOT(consume(QByteArray *)));
// they both get their own thread
QThread producerThread;
producer.moveToThread(&producerThread);
QThread consumerThread;
consumer.moveToThread(&consumerThread);
// go!
producerThread.start();
consumerThread.start();

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.