Boost Thread Qt Application: Difference between revisions

From Qt Wiki
Jump to navigation Jump to search
No edit summary
 
(3 intermediate revisions by 2 users not shown)
Line 1: Line 1:
[[Category:HowTo]]
[[Category:HowTo]]
== Introduction ==


= How-to launch Qt Application in a non-main thread =
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.


In this article I'll show how to manage running QApplication in a non-main thread. My need is to create an external shared library,
Anyway, I don't have control of the external process that loads my library, and I have to face the following two requirements:
that can offer a GUI interface when requested.


Anyway, I don't have control on 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


a) loading of my library is performed in a thread;
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.
b) 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,
Some basic ideas were taken from VLC source code.
'''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: :)


Here's just a sample of my solution, that has been extracted from my top-secret code :)
'''application.hpp'''


application.hpp file:
<code>
<code>
#ifndef APPLICATION_HPP
#ifndef APPLICATION_HPP
Line 36: Line 34:
  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);
QMutexLocker locker(&amp;_mutex);
  _eventProcessed = true;
_eventProcessed = true;
  _waitCondition.wakeAll();
_waitCondition.wakeAll();
  }
}


protected:
protected:
Application *qtApp() const { return _qtApp; }
  Application *qtApp() const { return _qtApp; }
  void customEvent(QEvent *event);


void customEvent(QEvent *event);
public:
  explicit DialogProvider(Application *qtApp, QObject *parent = 0) :
  QObject(parent), _qtApp(qtApp), _eventProcessed(false) {}


public:
  void waitForEventProcessed() {
explicit DialogProvider(Application *qtApp, QObject '''parent = 0) :
  QMutexLocker locker(&_mutex);
QObject(parent),
  if (!_eventProcessed) _waitCondition.wait(&_mutex);
_qtApp(qtApp),
  _eventProcessed = false;
_eventProcessed(false) { }
  }
 
void waitForEventProcessed()
{
QMutexLocker locker(&amp;_mutex);
if (!_eventProcessed)
_waitCondition.wait(&amp;_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,
  explicit ShowWaitDialogEvent(
int paramA, float paramB) :
  QEvent::Type eventType, int paramA, float paramB) :
QEvent(eventType),
  QEvent(eventType), _paramA(paramA), _paramB(paramB) {}
_paramA(paramA),
_paramB(paramB) { }


int paramA() const { return _paramA; }
  int paramA() const { return _paramA; }
float paramB() const { return _paramB; }
  float paramB() const { return _paramB; }
};
};


class Application : public QApplication
class Application : public QApplication
{
{
  DialogProvider'''_dpInstance;
  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;
 
protected:
virtual DialogProvider *createDialogProvider(Application *app)
{ return new DialogProvider(app,this); }
 
public:
explicit Application();


DialogProvider *dpInstance();
protected:
  virtual DialogProvider *createDialogProvider(Application *app) {
  return new DialogProvider(app,this);
  }


QEvent::Type showMyWidgetEventType() const { return _showMyWidgetEventType; }
public:
 
  explicit Application();
QEvent '''createShowMyWidgetEvent(int paramA, float paramB) const
  DialogProvider *dpInstance();
{ return new ShowMyWidgetEvent(showMyWidgetEventType(),paramA,paramB); }
  QEvent::Type showMyWidgetEventType() const { return _showMyWidgetEventType; }
  QEvent* createShowMyWidgetEvent(int paramA, float paramB) const {
  return new ShowMyWidgetEvent(showMyWidgetEventType(),paramA,paramB);
  }
};
};


class ThreadedApplication
class ThreadedApplication
{
{
  Application'''_app;
  Application* _app;
  volatile bool _started;
  volatile bool _started;
  boost::mutex _dialogMutex;
  boost::mutex _dialogMutex;
Line 118: Line 106:
  boost::condition_variable _applicationRunningCondition;
  boost::condition_variable _applicationRunningCondition;


protected:
protected:
Application *qtApp() const { return _app; }
  Application *qtApp() const { return _app; }
  virtual Application *createApplication() { return new Application(); }
  boost::mutex &dialogMutex() { return _dialogMutex; }


virtual Application *createApplication() { return new Application(); }
public:
  explicit ThreadedApplication() : _app(nullptr), _started(false) {}
  virtual ~ThreadedApplication() { stop(); }


boost::mutex &amp;dialogMutex() { return _dialogMutex; }
  void operator()();
 
public:
  explicit ThreadedApplication() :
_app(nullptr),
_started(false) { }
 
virtual ~ThreadedApplication() { stop(); }
 
void operator()();
  {
  {
if (!_app)
  if (!_app) {
{
  boost::unique_lock< boost::mutex > guard(_waitForApplicationRunningMutex);
boost::unique_lock< boost::mutex > guard(_waitForApplicationRunningMutex);
  _app = createApplication();
  _app->dpInstance();
  _started = true;
  _applicationRunningCondition.notify_all();
  }


_app = createApplication();
  _app->exec();
_app->dpInstance();
_started = true;
_applicationRunningCondition.notify_all();
  }
  }


_app->exec();
void waitForApplicationRun() {
  boost::unique_lock< boost::mutex > guard(_waitForApplicationRunningMutex);
  if (!_started) _applicationRunningCondition.wait(guard);
  }
  }


void waitForApplicationRun()
void stop() {
{
  if (_app) _app->quit();
boost::unique_lock< boost::mutex > guard(_waitForApplicationRunningMutex);
if (!_started)
_applicationRunningCondition.wait(guard);
  }
  }


void stop()
  void showMyWidget(int paramA, float paramB) {
{
  if (_app) {
if (_app)
  _app->postEvent(_app->dpInstance(),_app->createShowMyWidgetEvent(paramA,paramB));
  _app->quit();
  _app->dpInstance()->waitForEventProcessed();
}
  }
 
void showMyWidget(int paramA, float paramB)
{
if (_app)
{
_app->postEvent(_app->dpInstance(),_app->createShowMyWidgetEvent(paramA,paramB));
_app->dpInstance()->waitForEventProcessed();
}
  }
  }
};
};
Line 173: Line 148:
</code>
</code>


application.cpp file:
'''application.cpp'''


<code>
<code>
#include <boost/thread/locks.hpp>
#include <boost/thread/locks.hpp>
#include "application.hpp"
#include "application.hpp"


Line 186: Line 160:
void DialogProvider::customEvent(QEvent *event)
void DialogProvider::customEvent(QEvent *event)
{
{
  if (!_qtApp)
  if (!_qtApp) return;
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);
ShowMyWidgetEvent '''ev = static_cast< ShowMyWidgetEvent''' >(event);
  myWidget->show();
MyWidget *myWidget = new MyWidget(event->paramA(),event->paramB());
myWidget->setAttribute(Qt::WA_DeleteOnClose);
myWidget->show();
  }
  }


QObject::customEvent(event);
QObject::customEvent(event);
  signalEventProcessed();
  signalEventProcessed();
}
}
Line 211: Line 182:
DialogProvider *Application::dpInstance()
DialogProvider *Application::dpInstance()
{
{
  if (!_dpInstance)
  if (!_dpInstance) _dpInstance = createDialogProvider(this);
_dpInstance = createDialogProvider(this);
return _dpInstance;
 
return _dpInstance;
}
}
</code>
</code>
Line 241: Line 210:
</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[[Image:|Image:]] 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[[Image:|Image:]]! 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 deleteLater method.
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.


Comments on how to improve such solution are welcome[[Image:|Image:]]!
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.

Latest revision as of 20:59, 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:

  1. loading of my library is performed in a thread
  2. 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.