I try to extend an old program that runs under Ubuntu/Linux Desktop with a Qt-network support. Having a LAN communication with these libraries needs to run the .exec()
of the QEventLoop to really start working (i.e.: accept connections, receive, send, etc.)
The problem
Well the problem is I don't know where this event loop is in the main program and because I vaguely know about it's design I prefer a solution that is as indipendent as possible.
My idea
I already checked I don't need the main-QEventLoop, and it's alright to make another one just for the networking (i.e. nesting). Unfortunately I can't figure out how to run both loops in parallel, since my program stops at the nested-.exec()
and so the main program is on halt too.
So my main intention is actually to extend the main program with a Qt-Networking, I'm open for other solutions too.
Is the main program interactive? If it is, then likely it runs the glib main event loop. Qt uses the same event loop on Linux, so you don't need to call exec()
in your code. Prime the event loop only once by creating an instance of QEventLoop
, posting a quit call to it, and exec()
ing it. Then return control to the main program. Your code will still run as events arrive (timers time out, network packets arrive, etc.).
The wonderful thing about native event loop integration that you get with Qt is that you don't need to do the main exec()
if someone else is spinning the loop already.
So, here's how a Qt plugin to a GTK application on Linux might look like:
extern "C" void pluginInit() {
new QApplication;
QEventLoop loop;
QMetaObject::invokeMethod(&loop, "quit", Qt::QueuedConnection);
loop.exec();
}
extern "C" void pluginDestroy() {
delete qApp;
}
Once the plugin user calls pluginInit
, they can invoke any function in your plugin that uses Qt, and the events will be properly processed by the invoking application's event loop.
I'd prefer such a solution compared to threading, since it sounds more stable in general.
If threading is unstable for you, you're not doing it right. Networking support will run great on a dedicated thread. It's probably one of the few legitimate uses for a second thread, since that way your network data processing won't be delayed by the sweet time the userland renderer and compositor takes to put together what you see on the screen.