Qt 4.7 Emitting a signal to a specific thread - qt

I have several client GUI windows all derived from QMainWindow. Each window is potentially doing a different task but all are requesting data from a central cache implemented as a QThread.
All the clients connect to the same slot in the data cache and then emit signals to prompt the data cache to do something. The signals to the data cache get queued so the data cache only ever does one thing at a time.
When the data cache completes it needs to inform the correct client that the thing it was doing has completed. My immediate thought is to emit a signal to the requesting client about the completion. This would mean connecting to a specific client's slot and then emitting a signal to it.
Do I have to do connect and then disconnect to the client? I'm aware of the QObject::sender() function to get the supplier. Is there some way of emitting a signal to that sender (client) only? Or is there some other way of doing this?

There may be simpler approaches you can take to resolve your problem. For example, I would consider looking into the QtConcurrent framework. Alternately, you might also re-architect your design such that the client first connects to a "finished" signal on the cache prior to asking the cache to do anything. Failing all of that, you might also consider relying on the QMetaObject::invokeMethod function (for either your client or your cache). This function allows you to call an arbitrary method on an arbitrary QObject (provided that you have a pointer to it) using arbitrary generic arguments (in a way that's thread-safe).
If you use the QMetaObject::invokeMethod approach, there are a few of drawbacks you should be aware of. Firstly, you have to invoke the method using its string name, which means that you won't find out at compile time if you're using the wrong name. Secondly, since your clients have a different thread affinity than the central cache, there's a chance that the client will have been destroyed when the cache invokes the method on them (though perhaps in your case, this won't be a problem for you). Finally, you may not want your cache to have any knowledge of the names of the methods that it must execute on its client.
I don't have any way of getting around the first drawback (I'm not sure if this is going to be handled differently in the upcoming Qt 5.0 release). As far as the second and third problems, I would recommend creating an object that encapsulates a reference to a method -- something like the following:
class MethodReference
{
MethodReference(QObject* object, const QString& methodName);
...
bool invoke(QGenericArgument val0 = QGenericArgument(),
QGenericArgument val1 = QGenericArgument(),
...
QGenericArgument val9 = QGenericArgument());
private:
QPointer<QObject> mObject;
QString mMethod;
};
You would then pass this object to your cache from the client. The cache then calls invoke on this object.
Note the use of QPointer -- this gives you a thread-safe way of checking if your object has been destroyed before you try to invoke a method on it. Since I've done this before, I'll also let you know that versions of Qt prior to 4.8 had a bug in QPointer that would cause a crash in a multi-threaded context. Use a more recent version of Qt if you want to do this.
I hope this was clear.

Related

Accessing a thread un-safe COMobject in classic ASP

Trying to fix a problem in a classic ASP application, however I am inexperienced. Tried to find more info but was unable to.
The app instantiates a COM object for data retrieval which is not thread-safe, so the following instructions are added.
comObject=CreateObject("comServer.comObject")
returnValue=comObject.DoWork(.......)
...
comObject = Nothing
However, when processing two different http requests at the same time, the latter one seems to overwrite the first request, giving the first requester an error. It looks as if the comObject variable is shared between the requests.
How to instantiate the object in such a way that every separate request in IIS, gets it's own instance of the comObject?
Without knowing what the object does or how it does it, it's impossible to give specific advice. A general description will have to do:
The object is broken/buggy. It is the object's responsibility to handle the problem.
A COM object is supposed to handle all threading issues internally, or defer to COM STA apartments if it cannot do it, or doesn't want to (for those aspects that an STA can handle). This goes deep into the design of the object.
Regardless of COM Apartment choice, a DoWork(...) method with a semantic that precludes multiple separate COM objects in separate threads from handling simultaneous calls - is a seriously problematic design at best. A proper design would either include mechanisms to handle the conflict explicitly, or just hide the conflict from the calling code and handle the conflict internally.
Depending on the details of what DoWork() does, there might be ways to fix the object in such a way that the calls can succeed in parallel, or block each other so the calls are effectively serialized, or to cause the second call to throw a "You already called me" error. Again, which approach is more appropriate depends heavily on what the method does.
If you can't modify this broken component, your best option would be to write a COM wrapper that ensures serialization to the real object.
In any case, there is nothing reasonable you can do from the client (ASP VBScript) side.

QObject destructors not being called

I have two QObject child classes in my Qt application. One object from each of these classes was instantiated on the stack. Previously, my application would exit cleanly. However, since I've updated to Qt5.1.0, their destructors are not being called. I get the following warning twice when I launch the debugger.
the debug information found in "/usr/lib/debug//lib64/libfreebl3.so.debug"
does not match "/lib64/libfreebl3.so" (CRC mismatch)
Is this a bug in Qt or in my code?
See the documentation of QCoreApplication::exec:
We recommend that you connect clean-up code to the aboutToQuit() signal, instead of putting it in your application's main() function because on some platforms the QCoreApplication::exec() call may not return. For example, on Windows when the user logs off, the system terminates the process after Qt closes all top-level windows. Hence, there is no guarantee that the application will have time to exit its event loop and execute code at the end of the main() function after the QCoreApplication::exec() call.
You're using it incorrectly. It is not guaranteed that exec will be terminated after windows are closed. You should use aboutToQuit signal to stop other threads. If this signal is not emitted either, you need to call QApplication::quit() explicitly when your window is closed.
I'm not exactly sure in this case if this is a bug in your code or not, but anyway it is not recommended to create QObjects in the stack.
The reason is that the parent object (if any) will automatically call delete when destroyed, but then the object will also be automatically destroyed when it goes out of scope. Hence the object is destroyed twice which is Undefined Behaviour. That may explained why it worked well in one case, and not in another, since you can't rely on any consistent behaviour.
(But in your case it is weird that you say the destructor is not called at all...)

QObject based class has a queued connection to itself

I was digging into some source code I am working on. I found a peculiar statement that someone had coded. The source code is a GUI application with a QML GUI and uses QT 4.7.x.
The snippet below belongs to core application logic.
// connect signal-slots for decoupling
QObject::connect (this, SIGNAL(setCurrentTaskSignal(int)), this,
SLOT(SetCurrentTaskSlot(int)), Qt::QueuedConnection);
It's strange that the object connects to itself via a queued connection which essentially means that the object may "live" in different threads at the same time?
At first glance It didn't made any sense to me. Can anyone think of any reason why such a connection would be plausible or needed?. Would this even work?
It will work without any problem. Maybe there was some event loop processing required before calling SetCurrentTaskSlot?
Note that QueuedConnection doesn't mean that something is in different thread. QueuedConnection means only that when signal is emitted, corresponding slot won't be called directly. It will be queued on event loop, and will be processed when control will be given back to event loop
The queued connection implies nothing about where the receiver lives. The opposite is true: to safely send signals to an object living in another thread, you must use queued connections. But you can use them for an object living in any thread!
One uses a queued connection to ensure that the signal will be delivered from within the event loop, and not immediately from the emit site as happens with direct connection. Direct connection is conceptually a set of calls to function pointers on a list. Queued connection is conceptually an event sent to a clever receiver who can execute a function call based on the contents of the event.
The event is the internal QMetaCallEvent, and it is QObject::event that acts upon this event and executes the call.

QtCore dependence on QCoreApplication

I am trying to use Qt as a library (similar to this), because I want to reuse Qt classes in some currently non-Qt applications, and in shared libraries as cross-platform glue. Everything is non-GUI.
Some problems are easily avoided by DirectConnection, some can be solved with private event loops, even one can run a fake QCoreApplication in a thread and it works (last resort).
I want to know what modules rely on a running instance of QCoreApplication and cannot work without it.
Some of the Qt modules (in QtCore) do need an instance of QCoreApplication to run properly. For example QTimer relies on QCoreApplication to dispatch timer events.
I was reading the documentation for QtConcurrentRun and it seems to be relying on a global instance of QThreadPool, I am about to try and see if the application execution is vital, or maybe the instance is created on first access, or maybe not.
I am going to study QCoreApplicationPrivate source (Windows and Linux for now) but any hints in the right direction is greatly appreciated.
What are other functionality dependencies to the core application? Note that it might depend on the OS.
Edit1: Thanks to Kuba's answer, It seems QCoreApplication event loop is not necessary for timer and socket events to be dispatched. So some QtCore modules require and instance of QCoreApplication, but there is no need to have a running application event loop.
You are conflating the existence of a QCoreApplication with a running event loop. Those two are separate concepts. You may well need the former for the latter, but the latter doesn't have to run in the same thread as the former.
Most notably, you don't really have to call qApp->exec() if you don't have any events to dispatch in the thread where you constructed QCoreApplication.
The existence of a QCoreApplication is, as it were, a non-issue. Things get hairier with QApplication -- you can start it in a non-gui thread, but it's not portable and won't work on OS X. I'm trying to figure out why it doesn't work, but I don't have much time now to offer a satisfactory solution -- not yet.
It is also a misconception that QCoreApplication's event loop needs to be running for socket notifications and timer events to be dispatched to other threads. A QCoreApplication's event loop is nothing special. There is a platform-specific instance of QAbstractEventDispatcher that gets created for a thread when you instantiate the first QEventLoop in that thread. The QEventLoop doesn't know anything specific about the platform.
QCoreApplication's exec() method is quite simple and creates an instance of QEventLoop, and thus will create an instance of platform-specific QAbstractEventDispatcher. This instance is not special in any way. It's the same as any other event dispatcher created in any other thread, as far as my code reading tells so far.
If all underlying window systems would support it, it'd be in fact possible to make Qt GUI code multithreaded -- the per-thread event reception and dispatch is already there as a small first step. The big obstacle, probably the only one, would be the X library and its display lock. The display lock would be an obvious matter of contention between threads. You'd need each thread that wants to talk to the GUI open up a separate connection to the X server, and I don't know if there's a supported way of doing that from Xlib.

node.js asynchronous initialization issue

I am creating a node.js module which communicates with a program through XML-RPC. The API for this program changed recently after a certain version. For this reason, when a client is created (createClient) I want to ask the program its version (through XML-RPC) and base my API definitions on that.
The problem with this is that, because I do the above asynchronously, there exists a possibility that the work has not finished before the client is actually used. In other words:
var client = program.createClient();
client.doSomething();
doSomething() will fail because the API definitions have not been set, I imagine because HTTP XML-RPC response has not returned from the program.
What are some ways to remedy this? I want to be able to have a variable named client and work with that, as later I will be calling methods on it to get information (which will be returned via a callback).
Set it up this way:
program.createClient(function (client) {
client.doSomething()
})
Any time there is IO, it must be async. Another approach to this would be with a promise/future/coroutine type thing, but imo, just learning to love the callback is best :)

Resources