Boost Thread Qt Application

From Qt Wiki
Revision as of 20:59, 4 March 2015 by Simow (talk | contribs) (Simow moved page Boost thread qt application to Boost Thread Qt Application: Wording)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

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.