Boost Thread Qt Application: Difference between revisions
AutoSpider (talk | contribs) (Add "cleanup" tag) |
(Corrected Layout after Wiki Conversion) |
||
Line 1: | Line 1: | ||
[[Category:HowTo]] | [[Category:HowTo]] | ||
= | == Introduction == | ||
In this article I'll show how to manage running QApplication in a non-main thread. My | In this article I'll show how to manage running QApplication in a non-main thread. My approach is to create an external shared library, that can offer a GUI interface when requested. | ||
that can offer a GUI interface when requested. | |||
Anyway, I don't have control | Anyway, I don't have control of the external process that loads my library, and I have to face the following two requirements: | ||
# loading of my library is performed in a thread | |||
# calling of the public method that shows GUI interfaces happens in a different thread | |||
My solution requires the usage of boost::thread class (even if you can use any other thread-management technology, i.e. POSIX thread API, | My solution requires the usage of <tt>boost::thread</tt> class (even if you can use any other thread-management technology, i.e. POSIX thread API, '''but not QThread class'''). Boost Thread lets me preserve "code once, run everywhere" requirement. | ||
'''but not QThread class'''). Boost Thread lets me preserve "code once, run everywhere" requirement. | |||
Some basic ideas were taken from VLC source code. | Some basic ideas were taken from VLC source code. | ||
Here's just a sample of my solution, that has been extracted from my top-secret code :) | Here's just a sample of my solution, that has been extracted from my top-secret code: :) | ||
'''application.hpp''' | |||
<code> | <code> | ||
#ifndef APPLICATION_HPP | #ifndef APPLICATION_HPP | ||
Line 38: | Line 35: | ||
Q_OBJECT | Q_OBJECT | ||
Application *_qtApp; | Application *_qtApp; | ||
QWaitCondition _waitCondition; | QWaitCondition _waitCondition; | ||
QMutex _mutex; | QMutex _mutex; | ||
volatile bool _eventProcessed; | volatile bool _eventProcessed; | ||
void signalEventProcessed() | void signalEventProcessed() { | ||
QMutexLocker locker(&_mutex); | |||
_eventProcessed = true; | |||
_waitCondition.wakeAll(); | |||
} | |||
protected: | protected: | ||
Application *qtApp() const { return _qtApp; } | |||
void customEvent(QEvent *event); | |||
public: | |||
explicit DialogProvider(Application *qtApp, QObject *parent = 0) : | |||
QObject(parent), _qtApp(qtApp), _eventProcessed(false) {} | |||
void waitForEventProcessed() { | |||
QMutexLocker locker(&_mutex); | |||
if (!_eventProcessed) _waitCondition.wait(&_mutex); | |||
_eventProcessed = false; | |||
} | |||
}; | }; | ||
class ShowMyWidgetEvent : public QEvent | class ShowMyWidgetEvent : public QEvent { | ||
{ | |||
int _paramA; | int _paramA; | ||
float _paramB; | float _paramB; | ||
public: | public: | ||
explicit ShowWaitDialogEvent( | |||
QEvent::Type eventType, int paramA, float paramB) : | |||
QEvent(eventType), _paramA(paramA), _paramB(paramB) {} | |||
int paramA() const { return _paramA; } | |||
float paramB() const { return _paramB; } | |||
}; | }; | ||
class Application : public QApplication | class Application : public QApplication | ||
{ | { | ||
DialogProvider | DialogProvider* _dpInstance; | ||
static int staticArgc; | static int staticArgc; | ||
static char staticDummy[]; | static char staticDummy[]; | ||
static char *staticArgv[2]; | static char *staticArgv[2]; | ||
QEvent::Type _showMyWidgetEventType | QEvent::Type _showMyWidgetEventType; | ||
DialogProvider * | protected: | ||
virtual DialogProvider *createDialogProvider(Application *app) { | |||
return new DialogProvider(app,this); | |||
} | |||
QEvent::Type showMyWidgetEventType() const { return _showMyWidgetEventType; } | public: | ||
explicit Application(); | |||
QEvent | DialogProvider *dpInstance(); | ||
QEvent::Type showMyWidgetEventType() const { return _showMyWidgetEventType; } | |||
QEvent* createShowMyWidgetEvent(int paramA, float paramB) const { | |||
return new ShowMyWidgetEvent(showMyWidgetEventType(),paramA,paramB); | |||
} | |||
}; | }; | ||
class ThreadedApplication | class ThreadedApplication | ||
{ | { | ||
Application | Application* _app; | ||
volatile bool _started; | volatile bool _started; | ||
boost::mutex _dialogMutex; | boost::mutex _dialogMutex; | ||
Line 120: | Line 107: | ||
boost::condition_variable _applicationRunningCondition; | boost::condition_variable _applicationRunningCondition; | ||
protected: | protected: | ||
Application *qtApp() const { return _app; } | |||
virtual Application *createApplication() { return new Application(); } | |||
boost::mutex &dialogMutex() { return _dialogMutex; } | |||
virtual | public: | ||
explicit ThreadedApplication() : _app(nullptr), _started(false) {} | |||
virtual ~ThreadedApplication() { stop(); } | |||
void operator()(); | |||
void operator()(); | |||
{ | { | ||
if (!_app) { | |||
boost::unique_lock< boost::mutex > guard(_waitForApplicationRunningMutex); | |||
_app = createApplication(); | |||
_app->dpInstance(); | |||
_started = true; | |||
_applicationRunningCondition.notify_all(); | |||
} | |||
_app->exec(); | |||
} | } | ||
void waitForApplicationRun() { | |||
boost::unique_lock< boost::mutex > guard(_waitForApplicationRunningMutex); | |||
if (!_started) _applicationRunningCondition.wait(guard); | |||
} | } | ||
void | void stop() { | ||
if (_app) _app->quit(); | |||
} | } | ||
void showMyWidget(int paramA, float paramB) { | |||
if (_app) { | |||
_app->postEvent(_app->dpInstance(),_app->createShowMyWidgetEvent(paramA,paramB)); | |||
_app->dpInstance()->waitForEventProcessed(); | |||
} | |||
void showMyWidget(int paramA, float paramB) | |||
} | } | ||
}; | }; | ||
Line 175: | Line 149: | ||
</code> | </code> | ||
application.cpp | '''application.cpp''' | ||
<code> | <code> | ||
#include <boost/thread/locks.hpp> | #include <boost/thread/locks.hpp> | ||
#include "application.hpp" | #include "application.hpp" | ||
Line 188: | Line 161: | ||
void DialogProvider::customEvent(QEvent *event) | void DialogProvider::customEvent(QEvent *event) | ||
{ | { | ||
if (!_qtApp) | if (!_qtApp) return; | ||
if (event->type() == _qtApp->showMyWidgetEventType()) { | |||
ShowMyWidgetEvent *ev = static_cast< ShowMyWidgetEvent* >(event); | |||
if (event->type() == _qtApp->showMyWidgetEventType()) | MyWidget *myWidget = new MyWidget(event->paramA(),event->paramB()); | ||
myWidget->setAttribute(Qt::WA_DeleteOnClose); | |||
myWidget->show(); | |||
} | } | ||
QObject::customEvent(event); | QObject::customEvent(event); | ||
signalEventProcessed(); | signalEventProcessed(); | ||
} | } | ||
Line 213: | Line 183: | ||
DialogProvider *Application::dpInstance() | DialogProvider *Application::dpInstance() | ||
{ | { | ||
if (!_dpInstance) | if (!_dpInstance) _dpInstance = createDialogProvider(this); | ||
return _dpInstance; | |||
return _dpInstance; | |||
} | } | ||
</code> | </code> | ||
Line 243: | Line 211: | ||
</code> | </code> | ||
Of course, the two parameters are specified as example. "Thread C" posts a custom event (that carries on all information I need to create my widget) | Of course, the two parameters are specified as example. "Thread C" posts a custom event (that carries on all information I need to create my widget) to QApplication event loop, that forwards it to my DialogProvider customEvent method. In that method (I'm in QApplication context, i.e. "Thread B"), I can create my widget and show it in the end, I just signal (using a {{DocLink|QWaitCondition}}) that my widget is shown, so "Thread C" can return. | ||
to QApplication event loop, that forwards it to my DialogProvider customEvent method. | |||
In that method (I'm in QApplication context, i.e. "Thread B"), I can create my widget and show it | |||
that my widget is shown, so "Thread C" can return | |||
The final result is that all my Qt classes have been created in the QApplication thread context, just as a normal Qt application. Qt world is unaware of what has happened, and it never complains about anything. | |||
Just a warning about widgets creation and destruction in customEvent method. '''NEVER''' delete them there! QDialog based widgets can let you do wrong, cause usually you destroy the dialog just after executing them. Please use <tt>WA_DeleteOnClose</tt> attribute, as in my example, or defer their deletion using the deleteLater method. |
Revision as of 20:58, 4 March 2015
Introduction
In this article I'll show how to manage running QApplication in a non-main thread. My approach is to create an external shared library, that can offer a GUI interface when requested.
Anyway, I don't have control of the external process that loads my library, and I have to face the following two requirements:
- loading of my library is performed in a thread
- calling of the public method that shows GUI interfaces happens in a different thread
My solution requires the usage of boost::thread class (even if you can use any other thread-management technology, i.e. POSIX thread API, but not QThread class). Boost Thread lets me preserve "code once, run everywhere" requirement.
Some basic ideas were taken from VLC source code.
Here's just a sample of my solution, that has been extracted from my top-secret code: :)
application.hpp
#ifndef APPLICATION_HPP
#define APPLICATION_HPP
#include <boost/thread/thread.hpp>
#include <QObject>
#include <QApplication>
#include <QEvent>
#include <QWaitCondition>
#include <QMutex>
class Application;
class DialogProvider : public QObject
{
Q_OBJECT
Application *_qtApp;
QWaitCondition _waitCondition;
QMutex _mutex;
volatile bool _eventProcessed;
void signalEventProcessed() {
QMutexLocker locker(&_mutex);
_eventProcessed = true;
_waitCondition.wakeAll();
}
protected:
Application *qtApp() const { return _qtApp; }
void customEvent(QEvent *event);
public:
explicit DialogProvider(Application *qtApp, QObject *parent = 0) :
QObject(parent), _qtApp(qtApp), _eventProcessed(false) {}
void waitForEventProcessed() {
QMutexLocker locker(&_mutex);
if (!_eventProcessed) _waitCondition.wait(&_mutex);
_eventProcessed = false;
}
};
class ShowMyWidgetEvent : public QEvent {
int _paramA;
float _paramB;
public:
explicit ShowWaitDialogEvent(
QEvent::Type eventType, int paramA, float paramB) :
QEvent(eventType), _paramA(paramA), _paramB(paramB) {}
int paramA() const { return _paramA; }
float paramB() const { return _paramB; }
};
class Application : public QApplication
{
DialogProvider* _dpInstance;
static int staticArgc;
static char staticDummy[];
static char *staticArgv[2];
QEvent::Type _showMyWidgetEventType;
protected:
virtual DialogProvider *createDialogProvider(Application *app) {
return new DialogProvider(app,this);
}
public:
explicit Application();
DialogProvider *dpInstance();
QEvent::Type showMyWidgetEventType() const { return _showMyWidgetEventType; }
QEvent* createShowMyWidgetEvent(int paramA, float paramB) const {
return new ShowMyWidgetEvent(showMyWidgetEventType(),paramA,paramB);
}
};
class ThreadedApplication
{
Application* _app;
volatile bool _started;
boost::mutex _dialogMutex;
boost::mutex _waitForApplicationRunningMutex;
boost::condition_variable _applicationRunningCondition;
protected:
Application *qtApp() const { return _app; }
virtual Application *createApplication() { return new Application(); }
boost::mutex &dialogMutex() { return _dialogMutex; }
public:
explicit ThreadedApplication() : _app(nullptr), _started(false) {}
virtual ~ThreadedApplication() { stop(); }
void operator()();
{
if (!_app) {
boost::unique_lock< boost::mutex > guard(_waitForApplicationRunningMutex);
_app = createApplication();
_app->dpInstance();
_started = true;
_applicationRunningCondition.notify_all();
}
_app->exec();
}
void waitForApplicationRun() {
boost::unique_lock< boost::mutex > guard(_waitForApplicationRunningMutex);
if (!_started) _applicationRunningCondition.wait(guard);
}
void stop() {
if (_app) _app->quit();
}
void showMyWidget(int paramA, float paramB) {
if (_app) {
_app->postEvent(_app->dpInstance(),_app->createShowMyWidgetEvent(paramA,paramB));
_app->dpInstance()->waitForEventProcessed();
}
}
};
#endif
application.cpp
#include <boost/thread/locks.hpp>
#include "application.hpp"
int Application::staticArgc = 1;
char Application::staticDummy[] = "QtLibApplication";
char *Application::staticArgv[2] = { staticDummy, nullptr };
void DialogProvider::customEvent(QEvent *event)
{
if (!_qtApp) return;
if (event->type() == _qtApp->showMyWidgetEventType()) {
ShowMyWidgetEvent *ev = static_cast< ShowMyWidgetEvent* >(event);
MyWidget *myWidget = new MyWidget(event->paramA(),event->paramB());
myWidget->setAttribute(Qt::WA_DeleteOnClose);
myWidget->show();
}
QObject::customEvent(event);
signalEventProcessed();
}
Application::Application() :
QApplication(staticArgc,staticArgv),
_dpInstance(nullptr),
_showMyWidgetEventType(static_cast< QEvent::Type >(QEvent::registerEventType()))
{
setQuitOnLastWindowClosed(false);
}
DialogProvider *Application::dpInstance()
{
if (!_dpInstance) _dpInstance = createDialogProvider(this);
return _dpInstance;
}
My goal is to create my widget in the same thread of QApplication, as Qt requires, wait until the widget is shown, and let my widget run in the QApplication event loop context.
When one of my shared library public methods is called for the first time, I create an instance of the runnable ThreadedApplication class, and I fire it using boost::thread:
ThreadedApplication *app = new ThreadedApplication();
boost::thread appThread(boost::ref(*app));
app->waitForApplicationRun();
So, let's call "Thread A" the thread that executes the public method of my library, that performs the three lines above. A new thread is created (the "boost" one), called "Thread B", that creates an instance of QApplication, my DialogProvider, and executes event loop of QApplication, everything in the same context. "Thread A" is blocked until I'm sure that my application is started, then returns.
Some time later, a new thread, called "Thread C", wants to call a different public method that shows my widget. I just need to call
app->showMyWidget(5,3.0);
Of course, the two parameters are specified as example. "Thread C" posts a custom event (that carries on all information I need to create my widget) to QApplication event loop, that forwards it to my DialogProvider customEvent method. In that method (I'm in QApplication context, i.e. "Thread B"), I can create my widget and show it in the end, I just signal (using a QWaitCondition) that my widget is shown, so "Thread C" can return.
The final result is that all my Qt classes have been created in the QApplication thread context, just as a normal Qt application. Qt world is unaware of what has happened, and it never complains about anything.
Just a warning about widgets creation and destruction in customEvent method. NEVER delete them there! QDialog based widgets can let you do wrong, cause usually you destroy the dialog just after executing them. Please use WA_DeleteOnClose attribute, as in my example, or defer their deletion using the deleteLater method.