Boost Thread Qt Application: Difference between revisions

From Qt Wiki
Jump to navigation Jump to search
No edit summary
 
No edit summary
Line 1: Line 1:
=How-to launch Qt Application in a non-main thread=
[[Category:HowTo]]


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,<br /> that can offer a <span class="caps">GUI</span> interface when requested.
= How-to launch Qt Application in a non-main thread =


Anyway, I don’t have control on the external process that loads my library, and I have to face the following two requirements:
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,<br />that can offer a GUI interface when requested.


a) loading of my library is performed in a thread;<br /> b) calling of the public method that shows <span class="caps">GUI</span> interfaces happens in a different thread.
Anyway, I don't have control on the external process that loads my library, and I have to face the following two requirements:


My solution requires the usage of boost::thread class (even if you can use any other thread-management technology, i.e. <span class="caps">POSIX</span> thread <span class="caps">API</span>,<br />'''but not QThread class'''). Boost Thread lets me preserve “code once, run everywhere” requirement.
a) loading of my library is performed in a thread;<br />b) calling of the public method that shows GUI interfaces happens in a different thread.


Some basic ideas were taken from <span class="caps">VLC</span> source code.
My solution requires the usage of boost::thread class (even if you can use any other thread-management technology, i.e. POSIX thread API,<br />'''but not QThread class'''). Boost Thread lets me preserve &quot;code once, run everywhere&amp;quot; requirement.


Here’s just a sample of my solution, that has been extracted from my top-secret code <span class="smiley">:)</span>
Some basic ideas were taken from VLC source code.


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


application.cpp file:
application.hpp file:<br /><code><br />#ifndef APPLICATION_HPP<br />#define APPLICATION_HPP
 
#include &lt;boost/thread/thread.hpp&amp;gt;
 
#include &lt;QObject&amp;gt;<br />#include &lt;QApplication&amp;gt;<br />#include &lt;QEvent&amp;gt;<br />#include &lt;QWaitCondition&amp;gt;<br />#include &lt;QMutex&amp;gt;
 
class Application;<br />class DialogProvider : public QObject<br />{<br /> Q_OBJECT
 
Application *_qtApp;
 
QWaitCondition _waitCondition;<br /> QMutex _mutex;<br /> volatile bool _eventProcessed;
 
void signalEventProcessed()<br /> {<br /> QMutexLocker locker(&amp;_mutex);<br /> _eventProcessed = true;<br /> _waitCondition.wakeAll();<br /> }
 
protected:<br /> Application *qtApp() const { return _qtApp; }
 
void customEvent(QEvent *event);
 
public:<br /> explicit DialogProvider(Application *qtApp, QObject '''parent = 0) :<br /> QObject(parent),<br /> _qtApp(qtApp),<br /> _eventProcessed(false) { }
<br /> void waitForEventProcessed()<br /> {<br /> QMutexLocker locker(&amp;_mutex);<br /> if (!_eventProcessed)<br /> _waitCondition.wait(&amp;_mutex);<br /> _eventProcessed = false;<br /> }<br />};
<br />class ShowMyWidgetEvent : public QEvent<br />{<br /> int _paramA;<br /> float _paramB;
<br />public:<br /> explicit ShowWaitDialogEvent(QEvent::Type eventType,<br /> int paramA, float paramB) :<br /> QEvent(eventType),<br /> _paramA(paramA),<br /> _paramB(paramB) { }
<br /> int paramA() const { return _paramA; }<br /> float paramB() const { return _paramB; }<br />};
<br />class Application : public QApplication<br />{<br /> DialogProvider'''_dpInstance;
 
static int staticArgc;<br /> static char staticDummy[];<br /> static char *staticArgv[2];
 
QEvent::Type _showMyWidgetEventType;
 
protected:<br /> virtual DialogProvider *createDialogProvider(Application *app)<br /> { return new DialogProvider(app,this); }
 
public:<br /> explicit Application();
 
DialogProvider *dpInstance();
 
QEvent::Type showMyWidgetEventType() const { return _showMyWidgetEventType; }
 
QEvent '''createShowMyWidgetEvent(int paramA, float paramB) const<br /> { return new ShowMyWidgetEvent(showMyWidgetEventType(),paramA,paramB); }<br />};
<br />class ThreadedApplication<br />{<br /> Application'''_app;<br /> volatile bool _started;<br /> boost::mutex _dialogMutex;<br /> boost::mutex _waitForApplicationRunningMutex;<br /> boost::condition_variable _applicationRunningCondition;
 
protected:<br /> Application *qtApp() const { return _app; }
 
virtual Application *createApplication() { return new Application(); }
 
boost::mutex &amp;dialogMutex() { return _dialogMutex; }
 
public:<br /> explicit ThreadedApplication() :<br /> _app(nullptr),<br /> _started(false) { }
 
virtual ~ThreadedApplication() { stop(); }
 
void operator()();<br /> {<br /> if (!_app)<br /> {<br /> boost::unique_lock&amp;lt; boost::mutex &gt; guard(_waitForApplicationRunningMutex);
 
_app = createApplication();<br /> _app-&gt;dpInstance();<br /> _started = true;<br /> _applicationRunningCondition.notify_all();<br /> }
 
_app-&gt;exec&amp;amp;#40;&amp;#41;;<br /> }
 
void waitForApplicationRun()<br /> {<br /> boost::unique_lock&amp;lt; boost::mutex &gt; guard(_waitForApplicationRunningMutex);<br /> if (!_started)<br /> _applicationRunningCondition.wait(guard);<br /> }
 
void stop()<br /> {<br /> if (_app)<br /> _app-&gt;quit();<br /> }
 
void showMyWidget(int paramA, float paramB)<br /> {<br /> if (_app)<br /> {<br /> _app-&gt;postEvent(_app-&gt;dpInstance(),_app-&gt;createShowMyWidgetEvent(paramA,paramB));<br /> _app-&gt;dpInstance()<s>&gt;waitForEventProcessed();<br /> }<br /> }<br />};
<br />#endif<br /></code>
<br />application.cpp file:
<br /><code><br />#include &lt;boost/thread/locks.hpp&amp;gt;
<br />#include &quot;application.hpp&amp;quot;
<br />int Application::staticArgc = 1;<br />char Application::staticDummy[] = &quot;QtLibApplication&amp;quot;;<br />char *Application::staticArgv[2] = { staticDummy, nullptr };
<br />void DialogProvider::customEvent(QEvent *event)<br />{<br /> if (!_qtApp)<br /> return;
<br /> if (event</s>&gt;type() == _qtApp-&gt;showMyWidgetEventType())<br /> {<br /> ShowMyWidgetEvent '''ev = static_cast&amp;lt; ShowMyWidgetEvent''' &gt;(event);<br /> MyWidget *myWidget = new MyWidget(event-&gt;paramA(),event-&gt;paramB());<br /> myWidget-&gt;setAttribute(Qt::WA_DeleteOnClose);<br /> myWidget-&gt;show();<br /> }
 
QObject::customEvent(event);<br /> signalEventProcessed();<br />}
 
Application::Application() :<br /> QApplication(staticArgc,staticArgv),<br /> _dpInstance(nullptr),<br /> _showMyWidgetEventType(static_cast&amp;lt; QEvent::Type &gt;(QEvent::registerEventType()))<br />{<br /> setQuitOnLastWindowClosed(false);<br />}
 
DialogProvider *Application::dpInstance()<br />{<br /> if (!_dpInstance)<br /> _dpInstance = createDialogProvider(this);
 
return _dpInstance;<br />}<br /></code>


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.
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,<br /> I create an instance of the runnable ThreadedApplication class, and I fire it using boost::thread:
When one of my shared library public methods is called for the first time,<br />I create an instance of the runnable ThreadedApplication class, and I fire it using boost::thread:
 
So, let’s call “Thread A” the thread that executes the public method of my library, that performs the three lines above.<br /> A new thread is created (the “boost” one), called “Thread B”, that creates an instance of QApplication, my DialogProvider, and executes<br /> event loop of QApplication, everything in the same context.<br /> “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.<br /> I just need to call
<code><br />ThreadedApplication *app = new ThreadedApplication();<br />boost::thread appThread(boost::ref(*app));<br />app-&gt;waitForApplicationRun();<br /></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)<br /> to QApplication event loop, that forwards it to my DialogProvider customEvent method.<br /> 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)<br /> that my widget is shown, so “Thread C” can return.
So, let's call &quot;Thread A&amp;quot; the thread that executes the public method of my library, that performs the three lines above.<br />A new thread is created (the &quot;boost&amp;quot; one), called &quot;Thread B&amp;quot;, that creates an instance of QApplication, my DialogProvider, and executes<br />event loop of QApplication, everything in the same context.<br />&quot;Thread A&amp;quot; is blocked until I'm sure that my application is started, then returns.


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<br /> has happened, and it never complains about anything.
Some time later, a new thread, called &quot;Thread C&amp;quot;, wants to call a different public method that shows my widget.<br />I just need to call


Just a warning about widgets creation and destruction in customEvent method. '''<span class="caps">NEVER</span>''' 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 deleteLater method.
<code><br />app-&gt;showMyWidget(5,3.0);<br /></code>


Comments on how to improve such solution are welcome!!!
Of course, the two parameters are specified as example. &quot;Thread C&amp;quot; posts a custom event (that carries on all information I need to create my widget)<br />to QApplication event loop, that forwards it to my DialogProvider customEvent method.<br />In that method (I'm in QApplication context, i.e. &quot;Thread B&amp;quot;), I can create my widget and show it[[Image:|Image:]] In the end, I just signal (using a QWaitCondition)<br />that my widget is shown, so &quot;Thread C&amp;quot; can return.


Antonio Di Monaco
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<br />has happened, and it never complains about anything.


===Categories:===
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.


* [[:Category:HowTo|HowTo]]
Comments on how to improve such solution are welcome[[Image:|Image:]]!

Revision as of 09:42, 24 February 2015


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 need is to create an external shared library,
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:

a) loading of my library is performed in a thread;
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,
but not QThread class). Boost Thread lets me preserve "code once, run everywhere&quot; 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 file:

<br />#ifndef APPLICATION_HPP<br />#define APPLICATION_HPP

#include &lt;boost/thread/thread.hpp&amp;gt;

#include &lt;QObject&amp;gt;<br />#include &lt;QApplication&amp;gt;<br />#include &lt;QEvent&amp;gt;<br />#include &lt;QWaitCondition&amp;gt;<br />#include &lt;QMutex&amp;gt;

class Application;<br />class DialogProvider : public QObject<br />{<br /> Q_OBJECT

Application *_qtApp;

QWaitCondition _waitCondition;<br /> QMutex _mutex;<br /> volatile bool _eventProcessed;

void signalEventProcessed()<br /> {<br /> QMutexLocker locker(&amp;_mutex);<br /> _eventProcessed = true;<br /> _waitCondition.wakeAll();<br /> }

protected:<br /> Application *qtApp() const { return _qtApp; }

void customEvent(QEvent *event);

public:<br /> explicit DialogProvider(Application *qtApp, QObject '''parent = 0) :<br /> QObject(parent),<br /> _qtApp(qtApp),<br /> _eventProcessed(false) { }
<br /> void waitForEventProcessed()<br /> {<br /> QMutexLocker locker(&amp;_mutex);<br /> if (!_eventProcessed)<br /> _waitCondition.wait(&amp;_mutex);<br /> _eventProcessed = false;<br /> }<br />};
<br />class ShowMyWidgetEvent : public QEvent<br />{<br /> int _paramA;<br /> float _paramB;
<br />public:<br /> explicit ShowWaitDialogEvent(QEvent::Type eventType,<br /> int paramA, float paramB) :<br /> QEvent(eventType),<br /> _paramA(paramA),<br /> _paramB(paramB) { }
<br /> int paramA() const { return _paramA; }<br /> float paramB() const { return _paramB; }<br />};
<br />class Application : public QApplication<br />{<br /> DialogProvider'''_dpInstance;

static int staticArgc;<br /> static char staticDummy[];<br /> static char *staticArgv[2];

QEvent::Type _showMyWidgetEventType;

protected:<br /> virtual DialogProvider *createDialogProvider(Application *app)<br /> { return new DialogProvider(app,this); }

public:<br /> explicit Application();

DialogProvider *dpInstance();

QEvent::Type showMyWidgetEventType() const { return _showMyWidgetEventType; }

QEvent '''createShowMyWidgetEvent(int paramA, float paramB) const<br /> { return new ShowMyWidgetEvent(showMyWidgetEventType(),paramA,paramB); }<br />};
<br />class ThreadedApplication<br />{<br /> Application'''_app;<br /> volatile bool _started;<br /> boost::mutex _dialogMutex;<br /> boost::mutex _waitForApplicationRunningMutex;<br /> boost::condition_variable _applicationRunningCondition;

protected:<br /> Application *qtApp() const { return _app; }

virtual Application *createApplication() { return new Application(); }

boost::mutex &amp;dialogMutex() { return _dialogMutex; }

public:<br /> explicit ThreadedApplication() :<br /> _app(nullptr),<br /> _started(false) { }

virtual ~ThreadedApplication() { stop(); }

void operator()();<br /> {<br /> if (!_app)<br /> {<br /> boost::unique_lock&amp;lt; boost::mutex &gt; guard(_waitForApplicationRunningMutex);

_app = createApplication();<br /> _app-&gt;dpInstance();<br /> _started = true;<br /> _applicationRunningCondition.notify_all();<br /> }

_app-&gt;exec&amp;amp;#40;&amp;#41;;<br /> }

void waitForApplicationRun()<br /> {<br /> boost::unique_lock&amp;lt; boost::mutex &gt; guard(_waitForApplicationRunningMutex);<br /> if (!_started)<br /> _applicationRunningCondition.wait(guard);<br /> }

void stop()<br /> {<br /> if (_app)<br /> _app-&gt;quit();<br /> }

void showMyWidget(int paramA, float paramB)<br /> {<br /> if (_app)<br /> {<br /> _app-&gt;postEvent(_app-&gt;dpInstance(),_app-&gt;createShowMyWidgetEvent(paramA,paramB));<br /> _app-&gt;dpInstance()<s>&gt;waitForEventProcessed();<br /> }<br /> }<br />};
<br />#endif<br />


application.cpp file:


<br />#include &lt;boost/thread/locks.hpp&amp;gt;
<br />#include &quot;application.hpp&amp;quot;
<br />int Application::staticArgc = 1;<br />char Application::staticDummy[] = &quot;QtLibApplication&amp;quot;;<br />char *Application::staticArgv[2] = { staticDummy, nullptr };
<br />void DialogProvider::customEvent(QEvent *event)<br />{<br /> if (!_qtApp)<br /> return;
<br /> if (event</s>&gt;type() == _qtApp-&gt;showMyWidgetEventType())<br /> {<br /> ShowMyWidgetEvent '''ev = static_cast&amp;lt; ShowMyWidgetEvent''' &gt;(event);<br /> MyWidget *myWidget = new MyWidget(event-&gt;paramA(),event-&gt;paramB());<br /> myWidget-&gt;setAttribute(Qt::WA_DeleteOnClose);<br /> myWidget-&gt;show();<br /> }

QObject::customEvent(event);<br /> signalEventProcessed();<br />}

Application::Application() :<br /> QApplication(staticArgc,staticArgv),<br /> _dpInstance(nullptr),<br /> _showMyWidgetEventType(static_cast&amp;lt; QEvent::Type &gt;(QEvent::registerEventType()))<br />{<br /> setQuitOnLastWindowClosed(false);<br />}

DialogProvider *Application::dpInstance()<br />{<br /> if (!_dpInstance)<br /> _dpInstance = createDialogProvider(this);

return _dpInstance;<br />}<br />

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:

<br />ThreadedApplication *app = new ThreadedApplication();<br />boost::thread appThread(boost::ref(*app));<br />app-&gt;waitForApplicationRun();<br />

So, let's call "Thread A&quot; the thread that executes the public method of my library, that performs the three lines above.
A new thread is created (the "boost&quot; one), called "Thread B&quot;, that creates an instance of QApplication, my DialogProvider, and executes
event loop of QApplication, everything in the same context.
"Thread A&quot; is blocked until I'm sure that my application is started, then returns.

Some time later, a new thread, called "Thread C&quot;, wants to call a different public method that shows my widget.
I just need to call

<br />app-&gt;showMyWidget(5,3.0);<br />

Of course, the two parameters are specified as example. "Thread C&quot; 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&quot;), 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&quot; 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.

Comments on how to improve such solution are welcome[[Image:|Image:]]!