Sophie

Sophie

distrib > Mageia > 7 > x86_64 > by-pkgid > 1dd17e0d683ef79b4bb6872bbf359d7f > files > 7460

qt4-doc-4.8.7-26.2.mga7.noarch.rpm

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en_US" lang="en_US">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- threads.qdoc -->
  <title>Qt 4.8: Threading Basics</title>
  <link rel="stylesheet" type="text/css" href="style/style.css" />
  <script src="scripts/jquery.js" type="text/javascript"></script>
  <script src="scripts/functions.js" type="text/javascript"></script>
  <link rel="stylesheet" type="text/css" href="style/superfish.css" />
  <link rel="stylesheet" type="text/css" href="style/narrow.css" />
  <!--[if IE]>
<meta name="MSSmartTagsPreventParsing" content="true">
<meta http-equiv="imagetoolbar" content="no">
<![endif]-->
<!--[if lt IE 7]>
<link rel="stylesheet" type="text/css" href="style/style_ie6.css">
<![endif]-->
<!--[if IE 7]>
<link rel="stylesheet" type="text/css" href="style/style_ie7.css">
<![endif]-->
<!--[if IE 8]>
<link rel="stylesheet" type="text/css" href="style/style_ie8.css">
<![endif]-->

<script src="scripts/superfish.js" type="text/javascript"></script>
<script src="scripts/narrow.js" type="text/javascript"></script>

</head>
<body class="" onload="CheckEmptyAndLoadList();">
 <div class="header" id="qtdocheader">
    <div class="content"> 
    <div id="nav-logo">
      <a href="index.html">Home</a></div>
    <a href="index.html" class="qtref"><span>Qt Reference Documentation</span></a>
    <div id="narrowsearch"></div>
    <div id="nav-topright">
      <ul>
        <li class="nav-topright-home"><a href="http://qt.digia.com/">Qt HOME</a></li>
        <li class="nav-topright-dev"><a href="http://qt-project.org/">DEV</a></li>
        <li class="nav-topright-doc nav-topright-doc-active"><a href="http://qt-project.org/doc/">
          DOC</a></li>
        <li class="nav-topright-blog"><a href="http://blog.qt.digia.com/">BLOG</a></li>
      </ul>
    </div>
    <div id="shortCut">
      <ul>
        <li class="shortCut-topleft-inactive"><span><a href="index.html">Qt 4.8</a></span></li>
        <li class="shortCut-topleft-active"><a href="http://qt-project.org/doc/">ALL VERSIONS        </a></li>
      </ul>
     </div>
 <ul class="sf-menu" id="narrowmenu"> 
             <li><a href="#">API Lookup</a> 
                 <ul> 
                     <li><a href="classes.html">Class index</a></li> 
           <li><a href="functions.html">Function index</a></li> 
           <li><a href="modules.html">Modules</a></li> 
           <li><a href="namespaces.html">Namespaces</a></li> 
           <li><a href="qtglobal.html">Global Declarations</a></li> 
           <li><a href="qdeclarativeelements.html">QML elements</a></li> 
             </ul> 
             </li> 
             <li><a href="#">Qt Topics</a> 
                 <ul> 
                        <li><a href="qt-basic-concepts.html">Programming with Qt</a></li>  
                        <li><a href="qtquick.html">Device UIs &amp; Qt Quick</a></li>  
                        <li><a href="qt-gui-concepts.html">UI Design with Qt</a></li>  
                        <li><a href="supported-platforms.html">Supported Platforms</a></li>  
                        <li><a href="technology-apis.html">Qt and Key Technologies</a></li>  
                        <li><a href="best-practices.html">How-To's and Best Practices</a></li>  
              </ul> 
                 </li> 
                 <li><a href="#">Examples</a> 
                     <ul> 
                       <li><a href="all-examples.html">Examples</a></li> 
                       <li><a href="tutorials.html">Tutorials</a></li> 
                       <li><a href="demos.html">Demos</a></li> 
                       <li><a href="qdeclarativeexamples.html">QML Examples</a></li> 
                </ul> 
                     </li> 
                 </ul> 
    </div>
  </div>
  <div class="wrapper">
    <div class="hd">
      <span></span>
    </div>
    <div class="bd group">
      <div class="sidebar">
        <div class="searchlabel">
          Search index:</div>
        <div class="search" id="sidebarsearch">
          <form id="qtdocsearch" action="" onsubmit="return false;">
            <fieldset>
              <input type="text" name="searchstring" id="pageType" value="" />
 <div id="resultdialog"> 
 <a href="#" id="resultclose">Close</a> 
 <p id="resultlinks" class="all"><a href="#" id="showallresults">All</a> | <a href="#" id="showapiresults">API</a> | <a href="#" id="showarticleresults">Articles</a> | <a href="#" id="showexampleresults">Examples</a></p> 
 <p id="searchcount" class="all"><span id="resultcount"></span><span id="apicount"></span><span id="articlecount"></span><span id="examplecount"></span>&nbsp;results:</p> 
 <ul id="resultlist" class="all"> 
 </ul> 
 </div> 
            </fieldset>
          </form>
        </div>
        <div class="box first bottombar" id="lookup">
          <h2 title="API Lookup"><span></span>
            API Lookup</h2>
          <div  id="list001" class="list">
          <ul id="ul001" >
              <li class="defaultLink"><a href="classes.html">Class index</a></li>
              <li class="defaultLink"><a href="functions.html">Function index</a></li>
              <li class="defaultLink"><a href="modules.html">Modules</a></li>
              <li class="defaultLink"><a href="namespaces.html">Namespaces</a></li>
              <li class="defaultLink"><a href="qtglobal.html">Global Declarations</a></li>
              <li class="defaultLink"><a href="qdeclarativeelements.html">QML elements</a></li>
            </ul> 
          </div>
        </div>
        <div class="box bottombar" id="topics">
          <h2 title="Qt Topics"><span></span>
            Qt Topics</h2>
          <div id="list002" class="list">
            <ul id="ul002" >
               <li class="defaultLink"><a href="qt-basic-concepts.html">Programming with Qt</a></li> 
               <li class="defaultLink"><a href="qtquick.html">Device UIs &amp; Qt Quick</a></li> 
               <li class="defaultLink"><a href="qt-gui-concepts.html">UI Design with Qt</a></li> 
               <li class="defaultLink"><a href="supported-platforms.html">Supported Platforms</a></li>  
               <li class="defaultLink"><a href="technology-apis.html">Qt and Key Technologies</a></li> 
               <li class="defaultLink"><a href="best-practices.html">How-To's and Best Practices</a></li> 
            </ul>  
          </div>
        </div>
        <div class="box" id="examples">
          <h2 title="Examples"><span></span>
            Examples</h2>
          <div id="list003" class="list">
        <ul id="ul003">
              <li class="defaultLink"><a href="all-examples.html">Examples</a></li>
              <li class="defaultLink"><a href="tutorials.html">Tutorials</a></li>
              <li class="defaultLink"><a href="demos.html">Demos</a></li>
              <li class="defaultLink"><a href="qdeclarativeexamples.html">QML Examples</a></li>
            </ul> 
          </div>
        </div>
      </div>
      <div class="wrap">
        <div class="toolbar">
          <div class="breadcrumb toolblock">
            <ul>
              <li class="first"><a href="index.html">Home</a></li>
              <!--  Breadcrumbs go here -->
<li>Threading Basics</li>
            </ul>
          </div>
          <div class="toolbuttons toolblock">
            <ul>
              <li id="smallA" class="t_button">A</li>
              <li id="medA" class="t_button active">A</li>
              <li id="bigA" class="t_button">A</li>
              <li id="print" class="t_button"><a href="javascript:this.print();">
                <span>Print</span></a></li>
            </ul>
        </div>
        </div>
        <div class="content mainContent">
  <link rel="start" href="index.html" />
<p class="naviNextPrevious headerNavi">
</p><p/>
<div class="toc">
<h3><a name="toc">Contents</a></h3>
<ul>
<li class="level1"><a href="#what-are-threads">What Are Threads?</a></li>
<li class="level2"><a href="#gui-thread-and-worker-thread">GUI Thread and Worker Thread</a></li>
<li class="level2"><a href="#simultaneous-access-to-data">Simultaneous Access to Data</a></li>
<li class="level1"><a href="#using-threads">Using Threads</a></li>
<li class="level2"><a href="#when-to-use-alternatives-to-threads">When to Use Alternatives to Threads</a></li>
<li class="level2"><a href="#which-qt-thread-technology-should-you-use">Which Qt Thread Technology Should You Use?</a></li>
<li class="level1"><a href="#qt-thread-basics">Qt Thread Basics</a></li>
<li class="level2"><a href="#qobject-and-threads">QObject and Threads</a></li>
<li class="level2"><a href="#using-a-mutex-to-protect-the-integrity-of-data">Using a Mutex to Protect the Integrity of Data</a></li>
<li class="level2"><a href="#using-the-event-loop-to-prevent-data-corruption">Using the Event Loop to Prevent Data Corruption</a></li>
<li class="level2"><a href="#dealing-with-asynchronous-execution">Dealing with Asynchronous Execution</a></li>
<li class="level1"><a href="#examples">Examples</a></li>
<li class="level2"><a href="#example-1-using-the-thread-pool">Example 1: Using the Thread Pool</a></li>
<li class="level2"><a href="#example-2-using-qtconcurrent">Example 2: Using QtConcurrent</a></li>
<li class="level2"><a href="#example-3-clock">Example 3: Clock</a></li>
<li class="level2"><a href="#example-4-a-permanent-thread">Example 4: A Permanent Thread</a></li>
<li class="level1"><a href="#digging-deeper">Digging Deeper</a></li>
</ul>
</div>
<h1 class="title">Threading Basics</h1>
<span class="subtitle"></span>
<!-- $$$thread-basics.html-description -->
<div class="descr"> <a name="details"></a>
<a name="what-are-threads"></a>
<h2>What Are Threads?</h2>
<p>Threads are about doing things in parallel, just like processes. So how do threads differ from processes? While you are making calculations on a spreadsheet, there may also be a media player running on the same desktop playing your favorite song. Here is an example of two processes working in parallel: one running the spreadsheet program; one running a media player. Multitasking is a well known term for this. A closer look at the media player reveals that there are again things going on in parallel within one single process. While the media player is sending music to the audio driver, the user interface with all its bells and whistles is being constantly updated. This is what threads are for &mdash; concurrency within one single process.</p>
<p>So how is concurrency implemented? Parallel work on single core CPUs is an illusion which is somewhat similar to the illusion of moving images in cinema. For processes, the illusion is produced by interrupting the processor's work on one process after a very short time. Then the processor moves on to the next process. In order to switch between processes, the current program counter is saved and the next processor's program counter is loaded. This is not sufficient because the same needs to be done with registers and certain architecture and OS specific data.</p>
<p>Just as one CPU can power two or more processes, it is also possible to let the CPU run on two different code segments of one single process. When a process starts, it always executes one code segment and therefore the process is said to have one thread. However, the program may decide to start a second thread. Then, two different code sequences are processed simultaneously inside one process. Concurrency is achieved on single core CPUs by repeatedly saving program counters and registers then loading the next thread's program counters and registers. No cooperation from the program is required to cycle between the active threads. A thread may be in any state when the switch to the next thread occurs.</p>
<p>The current trend in CPU design is to have several cores. A typical single-threaded application can make use of only one core. However, a program with multiple threads can be assigned to multiple cores, making things happen in a truly concurrent way. As a result, distributing work to more than one thread can make a program run much faster on multicore CPUs because additional cores can be used.</p>
<a name="gui-thread-and-worker-thread"></a>
<h3>GUI Thread and Worker Thread</h3>
<p>As mentioned, each program has one thread when it is started. This thread is called the &quot;main thread&quot; (also known as the &quot;GUI thread&quot; in Qt applications). The Qt GUI must run in this thread. All widgets and several related classes, for example <a href="qpixmap.html">QPixmap</a>, don't work in secondary threads. A secondary thread is commonly referred to as a &quot;worker thread&quot; because it is used to offload processing work from the main thread.</p>
<a name="simultaneous-access-to-data"></a>
<h3>Simultaneous Access to Data</h3>
<p>Each thread has its own stack, which means each thread has its own call history and local variables. Unlike processes, threads share the same address space. The following diagram shows how the building blocks of threads are located in memory. Program counter and registers of inactive threads are typically kept in kernel space. There is a shared copy of the code and a separate stack for each thread.</p>
<p class="centerAlign"><img src="images/threadvisual-example.png" alt="&quot;Thread visualization&quot;" /></p><p>If two threads have a pointer to the same object, it is possible that both threads will access that object at the same time and this can potentially destroy the object's integrity. It's easy to imagine the many things that can go wrong when two methods of the same object are executed simultaneously.</p>
<p>Sometimes it is necessary to access one object from different threads; for example, when objects living in different threads need to communicate. Since threads use the same address space, it is easier and faster for threads to exchange data than it is for processes. Data does not have to be serialized and copied. Passing pointers is possible, but there must be a strict coordination of what thread touches which object. Simultaneous execution of operations on one object must be prevented. There are several ways of achieving this and some of them are described below.</p>
<p>So what can be done safely? All objects created in a thread can be used safely within that thread provided that other threads don't have references to them and objects don't have implicit coupling with other threads. Such implicit coupling may happen when data is shared between instances as with static members, singletons or global data. Familiarize yourself with the concept of <a href="threads-reentrancy.html">thread safe and reentrant</a> classes and functions.</p>
<a name="using-threads"></a>
<h2>Using Threads</h2>
<p>There are basically two use cases for threads:</p>
<ul>
<li>Make processing faster by making use of multicore processors.</li>
<li>Keep the GUI thread or other time critical threads responsive by offloading long lasting processing or blocking calls to other threads.</li>
</ul>
<a name="when-to-use-alternatives-to-threads"></a>
<h3>When to Use Alternatives to Threads</h3>
<p>Developers need to be very careful with threads. It is easy to start other threads, but very hard to ensure that all shared data remains consistent. Problems are often hard to find because they may only show up once in a while or only on specific hardware configurations. Before creating threads to solve certain problems, possible alternatives should be considered.</p>
<table class="generic">
<thead><tr class="qt-style"><th >Alternative</th><th >Comment</th></tr></thead>
<tr valign="top" class="odd"><td ><a href="qeventloop.html#processEvents">QEventLoop::processEvents</a>()</td><td >Calling <a href="qeventloop.html#processEvents">QEventLoop::processEvents</a>() repeatedly during a time-consuming calculation prevents GUI blocking. However, this solution doesn't scale well because the call to processEvents() may occur too often, or not often enough, depending on hardware.</td></tr>
<tr valign="top" class="even"><td ><a href="qtimer.html">QTimer</a></td><td >Background processing can sometimes be done conveniently using a timer to schedule execution of a slot at some point in the future. A timer with an interval of 0 will time out as soon as there are no more events to process.</td></tr>
<tr valign="top" class="odd"><td ><a href="qsocketnotifier.html">QSocketNotifier</a> <a href="qnetworkaccessmanager.html">QNetworkAccessManager</a> <a href="qiodevice.html#readyRead">QIODevice::readyRead</a>()</td><td >This is an alternative to having one or multiple threads, each with a blocking read on a slow network connection. As long as the calculation in response to a chunk of network data can be executed quickly, this reactive design is better than synchronous waiting in threads. Reactive design is less error prone and energy efficient than threading. In many cases there are also performance benefits.</td></tr>
</table>
<p>In general, it is recommended to only use safe and tested paths and to avoid introducing ad-hoc threading concepts. <a href="qtconcurrent.html">QtConcurrent</a> provides an easy interface for distributing work to all of the processor's cores. The threading code is completely hidden in the <a href="qtconcurrent.html">QtConcurrent</a> framework, so you don't have to take care of the details. However, <a href="qtconcurrent.html">QtConcurrent</a> can't be used when communication with the running thread is needed, and it shouldn't be used to handle blocking operations.</p>
<a name="which-qt-thread-technology-should-you-use"></a>
<h3>Which Qt Thread Technology Should You Use?</h3>
<p>Sometimes you want to do more than just running a method in the context of another thread. You may want to have an object which lives in another thread that provides a service to the GUI thread. Maybe you want another thread to stay alive forever to poll hardware ports and send a signal to the GUI thread when something noteworthy has happened. Qt provides different solutions for developing threaded applications. The right solution depends on the purpose of the new thread as well as on the thread's lifetime.</p>
<table class="generic">
<thead><tr class="qt-style"><th >Lifetime of thread</th><th >Development task</th><th >Solution</th></tr></thead>
<tr valign="top" class="odd"><td >One call</td><td >Run one method within another thread and quit the thread when the method is finished.</td><td >Qt provides different solutions:<ul>
<li>Write a function and run it with <a href="qtconcurrentrun.html#run">QtConcurrent::run</a>()</li>
<li>Derive a class from <a href="qrunnable.html">QRunnable</a> and run it in the global thread pool with <a href="qthreadpool.html#globalInstance">QThreadPool::globalInstance</a>()-&gt;start()</li>
<li>Derive a class from <a href="qthread.html">QThread</a>, reimplement the <a href="qthread.html#run">QThread::run</a>() method and use <a href="qthread.html#start">QThread::start</a>() to run it.</li>
</ul>
</td></tr>
<tr valign="top" class="even"><td >One call</td><td >Operations are to be performed on all items of a container. Processing should be performed using all available cores. A common example is to produce thumbnails from a list of images.</td><td ><a href="qtconcurrent.html">QtConcurrent</a> provides the <a href="qtconcurrentmap.html#map">map()</a> function for applying operations on every container element, <a href="qtconcurrentfilter.html#filter">filter()</a> for selecting container elements, and the option of specifying a reduce function for combining the remaining elements.</td></tr>
<tr valign="top" class="odd"><td >One call</td><td >A long running operation has to be put in another thread. During the course of processing, status information should be sent to the GUI thread.</td><td >Use <a href="qthread.html">QThread</a>, reimplement run and emit signals as needed. Connect the signals to the GUI thread's slots using queued signal/slot connections.</td></tr>
<tr valign="top" class="even"><td >Permanent</td><td >Have an object living in another thread and let it perform different tasks upon request. This means communication to and from the worker thread is required.</td><td >Derive a class from <a href="qobject.html">QObject</a> and implement the necessary slots and signals, move the object to a thread with a running event loop and communicate with the object over queued signal/slot connections.</td></tr>
<tr valign="top" class="odd"><td >Permanent</td><td >Have an object living in another thread, let the object perform repeated tasks such as polling a port and enable communication with the GUI thread.</td><td >Same as above but also use a timer in the worker thread to implement polling. However, the best solution for polling is to avoid it completely. Sometimes using <a href="qsocketnotifier.html">QSocketNotifier</a> is an alternative.</td></tr>
</table>
<a name="qt-thread-basics"></a>
<h2>Qt Thread Basics</h2>
<p><a href="qthread.html">QThread</a> is a very convenient cross platform abstraction of native platform threads. Starting a thread is very simple. Let us look at a short piece of code that generates another thread which says hello in that thread and then exits.</p>
<pre class="cpp"> <span class="comment">// hellothread/hellothread.h</span>
 <span class="keyword">class</span> HelloThread : <span class="keyword">public</span> <span class="type"><a href="qthread.html">QThread</a></span>
 {
     Q_OBJECT
 <span class="keyword">private</span>:
     <span class="type">void</span> run();
 };</pre>
<p>We derive a class from <a href="qthread.html">QThread</a> and reimplement the <a href="qthread.html#run">run()</a> method.</p>
<pre class="cpp"> <span class="comment">// hellothread/hellothread.cpp</span>
 <span class="type">void</span> HelloThread<span class="operator">::</span>run()
 {
      <a href="qtglobal.html#qDebug">qDebug</a>() <span class="operator">&lt;</span><span class="operator">&lt;</span> <span class="string">&quot;hello from worker thread &quot;</span> <span class="operator">&lt;</span><span class="operator">&lt;</span> thread()<span class="operator">-</span><span class="operator">&gt;</span>currentThreadId();
 }</pre>
<p>The run method contains the code that will be run in a separate thread. In this example, a message containing the thread ID will be printed. <a href="qthread.html#start">QThread::start</a>() will call the method in another thread.</p>
<pre class="cpp"> <span class="type">int</span> main(<span class="type">int</span> argc<span class="operator">,</span> <span class="type">char</span> <span class="operator">*</span>argv<span class="operator">[</span><span class="operator">]</span>)
 {
     <span class="type"><a href="qcoreapplication.html">QCoreApplication</a></span> app(argc<span class="operator">,</span> argv);
     HelloThread thread;
     thread<span class="operator">.</span>start();
     <a href="qtglobal.html#qDebug">qDebug</a>() <span class="operator">&lt;</span><span class="operator">&lt;</span> <span class="string">&quot;hello from GUI thread &quot;</span> <span class="operator">&lt;</span><span class="operator">&lt;</span> app<span class="operator">.</span>thread()<span class="operator">-</span><span class="operator">&gt;</span>currentThreadId();
     thread<span class="operator">.</span>wait();  <span class="comment">// do not exit before the thread is completed!</span>
     <span class="keyword">return</span> <span class="number">0</span>;
 }</pre>
<p>To start the thread, our thread object needs to be instantiated. The <a href="qthread.html#start">start()</a> method creates a new thread and calls the reimplemented <a href="qthread.html#run">run()</a> method in this new thread. Right after <a href="qthread.html#start">start()</a> is called, two program counters walk through the program code. The main function starts with only the GUI thread running and it should terminate with only the GUI thread running. Exiting the program when another thread is still busy is a programming error, and therefore, wait is called which blocks the calling thread until the <a href="qthread.html#run">run()</a> method has completed.</p>
<p>This is the result of running the code:</p>
<pre class="cpp"> hello from GUI thread  3079423696
 hello from worker thread  3076111216</pre>
<a name="qobject-and-threads"></a>
<h3>QObject and Threads</h3>
<p>As mentioned above, developers must always be careful when calling objects' methods from other threads. <a href="qobject.html#thread-affinity">Thread affinity</a> does not change this situation. Qt documentation marks several methods as thread-safe. <a href="qcoreapplication.html#postEvent">postEvent()</a> is a noteworthy example. A thread-safe method may be called from different threads simultaneously.</p>
<p>In cases where there is usually no concurrent access to methods, calling non-thread-safe methods of objects in other threads may work thousands of times before a concurrent access occurs, causing unexpected behavior. Writing test code does not entirely ensure thread correctness, but it is still important. On Linux, Valgrind and Helgrind can help detect threading errors.</p>
<a name="using-a-mutex-to-protect-the-integrity-of-data"></a>
<h3>Using a Mutex to Protect the Integrity of Data</h3>
<p>A mutex is an object that has <a href="qmutex.html#lock">lock()</a> and <a href="qmutex.html#unlock">unlock()</a> methods and remembers if it is already locked. A mutex is designed to be called from multiple threads. <a href="qmutex.html#lock">lock()</a> returns immediately if the mutex is not locked. The next call from another thread will find the mutex in a locked state and then <a href="qmutex.html#lock">lock()</a> will block the thread until the other thread calls <a href="qmutex.html#unlock">unlock()</a>. This functionality can make sure that a code section will be executed by only one thread at a time.</p>
<p>The following line sketches how a mutex can be used to make a method thread-safe:</p>
<pre class="cpp"> <span class="type">void</span> Worker<span class="operator">::</span>work()
 {
     <span class="keyword">this</span><span class="operator">-</span><span class="operator">&gt;</span>mutex<span class="operator">.</span>lock();  <span class="comment">// first thread can pass, other threads will be blocked here</span>
     doWork();
     <span class="keyword">this</span><span class="operator">-</span><span class="operator">&gt;</span>mutex<span class="operator">.</span>unlock();
 }</pre>
<p>What happens if one thread does not unlock a mutex? The result can be a frozen application. In the example above, an exception might be thrown and <tt>mutex.unlock()</tt> will never be reached. To prevent problems like this, <a href="qmutexlocker.html">QMutexLocker</a> should be used.</p>
<pre class="cpp"> <span class="type">void</span> Worker<span class="operator">::</span>work()
 {
     <span class="type"><a href="qmutexlocker.html">QMutexLocker</a></span> locker(<span class="operator">&amp;</span>mutex);  <span class="comment">// Locks the mutex and unlocks when locker exits the scope</span>
     doWork();
 }</pre>
<p>This looks easy, but mutexes introduce a new class of problems: deadlocks. A deadlock happens when a thread waits for a mutex to become unlocked, but the mutex remains locked because the owning thread is waiting for the first thread to unlock it. The result is a frozen application. Mutexes can be used to make a method thread safe. Most Qt methods aren't thread safe because there is always a performance penalty when using mutexes.</p>
<p>It isn't always possible to lock and unlock a mutex in a method. Sometimes the need to lock spans several calls. For example, modifying a container with an iterator requires a sequence of several calls which should not be interrupted by other threads. In such a scenario, locking can be achieved with a mutex that is kept outside of the object to be manipulated. With an external mutex, the duration of locking can be adjusted to the needs of the operation. One disadvantage is that external mutexes aid locking, but do not enforce it because users of the object may forget to use it.</p>
<a name="using-the-event-loop-to-prevent-data-corruption"></a>
<h3>Using the Event Loop to Prevent Data Corruption</h3>
<p>The event loops of Qt are a very valuable tool for inter-thread communication. Every thread may have its own event loop. A safe way of calling a slot in another thread is by placing that call in another thread's event loop. This ensures that the target object finishes the method that is currently running before another method is started.</p>
<p>So how is it possible to put a method invocation in an event loop? Qt has two ways of doing this. One way is via queued signal-slot connections; the other way is to post an event with <a href="qcoreapplication.html#postEvent">QCoreApplication::postEvent</a>(). A queued signal-slot connection is a signal slot connection that is executed asynchronously. The internal implementation is based on posted events. The arguments of the signal are put into the event loop and the signal method returns immediately.</p>
<p>The connected slot will be executed at a time which depends on what else is in the event loop.</p>
<p>Communication via the event loop eliminates the deadlock problem we face when using mutexes. This is why we recommend using the event loop rather than locking an object using a mutex.</p>
<a name="dealing-with-asynchronous-execution"></a>
<h3>Dealing with Asynchronous Execution</h3>
<p>One way to obtain a worker thread's result is by waiting for the thread to terminate. In many cases, however, a blocking wait isn't acceptable. The alternative to a blocking wait are asynchronous result deliveries with either posted events or queued signals and slots. This generates a certain overhead because an operation's result does not appear on the next source line, but in a slot located somewhere else in the source file. Qt developers are used to working with this kind of asynchronous behavior because it is much similar to the kind of event-driven programming used in GUI applications.</p>
<a name="examples"></a>
<h2>Examples</h2>
<p>This tutorial comes with examples for Qt's three basic ways of working with threads. Two more examples show how to communicate with a running thread and how a <a href="qobject.html">QObject</a> can be placed in another thread, providing service to the main thread.</p>
<ul>
<li>Using <a href="qthread.html">QThread</a> as shown <a href="#qt-thread-basics">above</a></li>
<li><a href="#example-1-using-the-thread-pool">Using the global QThreadPool</a></li>
<li><a href="#example-2-using-qtconcurrent">Using QtConcurrent</a></li>
<li><a href="#example-3-clock">Communication with the GUI thread</a></li>
<li><a href="#example-4-a-permanent-thread">A permanent QObject in another thread provides service to the main thread</a></li>
</ul>
<p>The following examples can all be compiled and run independently. The source can be found in the examples directory: examples/tutorials/threads/</p>
<a name="example-1-using-the-thread-pool"></a>
<h3>Example 1: Using the Thread Pool</h3>
<p>Creating and destroying threads frequently can be expensive. To avoid the cost of thread creation, a thread pool can be used. A thread pool is a place where threads can be parked and fetched. We can write the same &quot;hello thread&quot; program as <a href="#qt-thread-basics">above</a> using the global thread pool. We derive a class from <a href="qrunnable.html">QRunnable</a>. The code we want to run in another thread needs to be placed in the reimplemented <a href="qrunnable.html#run">QRunnable::run</a>() method.</p>
<pre class="cpp"> <span class="comment">// hellothreadpool/main.cpp</span>
 <span class="keyword">class</span> Work : <span class="keyword">public</span> <span class="type"><a href="qrunnable.html">QRunnable</a></span>
 {
 <span class="keyword">public</span>:
     <span class="type">void</span> run()
     {
         <a href="qtglobal.html#qDebug">qDebug</a>() <span class="operator">&lt;</span><span class="operator">&lt;</span> <span class="string">&quot;Hello from thread &quot;</span> <span class="operator">&lt;</span><span class="operator">&lt;</span> <span class="type"><a href="qthread.html">QThread</a></span><span class="operator">::</span>currentThread();
     }
 };

 <span class="type">int</span> main(<span class="type">int</span> argc<span class="operator">,</span> <span class="type">char</span> <span class="operator">*</span>argv<span class="operator">[</span><span class="operator">]</span>)
 {
     <span class="type"><a href="qcoreapplication.html">QCoreApplication</a></span> app(argc<span class="operator">,</span> argv);
     Work work;
     work<span class="operator">.</span>setAutoDelete(<span class="keyword">false</span>);
     <span class="type"><a href="qthreadpool.html">QThreadPool</a></span> <span class="operator">*</span>threadPool <span class="operator">=</span> <span class="type"><a href="qthreadpool.html">QThreadPool</a></span><span class="operator">::</span>globalInstance();
     threadPool<span class="operator">-</span><span class="operator">&gt;</span>start(<span class="operator">&amp;</span>work);
     <a href="qtglobal.html#qDebug">qDebug</a>() <span class="operator">&lt;</span><span class="operator">&lt;</span> <span class="string">&quot;hello from GUI thread &quot;</span> <span class="operator">&lt;</span><span class="operator">&lt;</span> <span class="type"><a href="qthread.html">QThread</a></span><span class="operator">::</span>currentThread();
     threadPool<span class="operator">-</span><span class="operator">&gt;</span>waitForDone();
     <span class="keyword">return</span> <span class="number">0</span>;
 }</pre>
<p>We instantiate Work in main(), locate the global thread pool and use the <a href="qthreadpool.html#start">QThreadPool::start</a>() method. Now the thread pool runs our worker in another thread. Using the thread pool has a performance advantage because threads are not destroyed after they have finished running. They are kept in a pool and wait to be used again later.</p>
<a name="example-2-using-qtconcurrent"></a>
<h3>Example 2: Using QtConcurrent</h3>
<pre class="cpp"> <span class="comment">// helloconcurrent/main.cpp</span>
 <span class="type">void</span> hello()
 {
     <a href="qtglobal.html#qDebug">qDebug</a>() <span class="operator">&lt;</span><span class="operator">&lt;</span> <span class="string">&quot;Hello from thread &quot;</span> <span class="operator">&lt;</span><span class="operator">&lt;</span> <span class="type"><a href="qthread.html">QThread</a></span><span class="operator">::</span>currentThread();
 }

 <span class="type">int</span> main(<span class="type">int</span> argc<span class="operator">,</span> <span class="type">char</span> <span class="operator">*</span>argv<span class="operator">[</span><span class="operator">]</span>)
 {
     <span class="type"><a href="qcoreapplication.html">QCoreApplication</a></span> app(argc<span class="operator">,</span> argv);
     <span class="type"><a href="qfuture.html">QFuture</a></span><span class="operator">&lt;</span><span class="type">void</span><span class="operator">&gt;</span> future <span class="operator">=</span> <span class="type"><a href="qtconcurrent.html">QtConcurrent</a></span><span class="operator">::</span>run(hello);
     <a href="qtglobal.html#qDebug">qDebug</a>() <span class="operator">&lt;</span><span class="operator">&lt;</span> <span class="string">&quot;hello from GUI thread &quot;</span> <span class="operator">&lt;</span><span class="operator">&lt;</span> <span class="type"><a href="qthread.html">QThread</a></span><span class="operator">::</span>currentThread();
     future<span class="operator">.</span>waitForFinished();
     <span class="keyword">return</span> <span class="number">0</span>;
 }</pre>
<p>We write a global function hello() to implement the work. <a href="qtconcurrentrun.html#run">QtConcurrent::run</a>() is used to run the function in another thread. The result is a <a href="qfuture.html">QFuture</a>. <a href="qfuture.html">QFuture</a> provides a method called <a href="qfuture.html#waitForFinished">waitForFinished()</a>, which blocks until the calculation is completed. The real power of <a href="qtconcurrent.html">QtConcurrent</a> becomes visible when data can be made available in a container. <a href="qtconcurrent.html">QtConcurrent</a> provides several functions that are able to process itemized data on all available cores simultaneously. The use of <a href="qtconcurrent.html">QtConcurrent</a> is very similar to applying an STL algorithm to an STL container. <a href="examples-threadandconcurrent.html">QtConcurrent Map</a> is a very short and clear example about how a container of images can be scaled on all available cores. The image scaling example uses the blocking variants of the functions used. For every blocking function there is also a non-blocking, asynchronous counterpart. Getting results asynchronously is implemented with <a href="qfuture.html">QFuture</a> and <a href="qfuturewatcher.html">QFutureWatcher</a>.</p>
<a name="example-3-clock"></a>
<h3>Example 3: Clock</h3>
<p class="centerAlign"><img src="images/thread_clock.png" alt="&quot;clock&quot;" /></p><p>We want to produce a clock application. The application has a GUI and a worker thread. The worker thread checks every 10 milliseconds what time it is. If the formatted time has changed, the result will be sent to the GUI thread where it is displayed.</p>
<p>Of course, this is an overly complicated way of designing a clock and, actually, a separate thread is unnecessary. We would be better off placing the timer in the main thread because the calculation made in the timer slot is very short-lived. This example is purely for instructional use and shows how to communicate from a worker thread to a GUI thread. Note that communication in this direction is easy. We only need to add a signal to <a href="qthread.html">QThread</a> and make a queued signal/slot connection to the main thread. Communication from the GUI to the worker thread is shown in the next example.</p>
<pre class="cpp"> <span class="type">int</span> main(<span class="type">int</span> argc<span class="operator">,</span> <span class="type">char</span> <span class="operator">*</span>argv<span class="operator">[</span><span class="operator">]</span>)
 {
     <span class="type"><a href="qapplication.html">QApplication</a></span> app(argc<span class="operator">,</span> argv);
     <span class="comment">// build gui</span>
     <span class="type"><a href="qwidget.html">QWidget</a></span> widget;
     <span class="type"><a href="qlabel.html">QLabel</a></span> <span class="operator">*</span>label <span class="operator">=</span> <span class="keyword">new</span> <span class="type"><a href="qlabel.html">QLabel</a></span>;
     <span class="type"><a href="qhboxlayout.html">QHBoxLayout</a></span> <span class="operator">*</span>layout <span class="operator">=</span> <span class="keyword">new</span> <span class="type"><a href="qhboxlayout.html">QHBoxLayout</a></span>(<span class="operator">&amp;</span>widget);
     layout<span class="operator">-</span><span class="operator">&gt;</span>addWidget(label);
     widget<span class="operator">.</span>setWindowTitle(<span class="string">&quot;clock&quot;</span>);

     <span class="comment">//instantiate thread object</span>
     ClockThread clockThread;
     <span class="type"><a href="qobject.html">QObject</a></span><span class="operator">::</span>connect(<span class="operator">&amp;</span>clockThread<span class="operator">,</span> SIGNAL(sendTime(<span class="type"><a href="qstring.html">QString</a></span>))<span class="operator">,</span> label<span class="operator">,</span> SLOT(setText(<span class="type"><a href="qstring.html">QString</a></span>))<span class="operator">,</span> <span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>QueuedConnection);
     clockThread<span class="operator">.</span>start();
     widget<span class="operator">.</span>show();
     app<span class="operator">.</span>exec();
     clockThread<span class="operator">.</span>quit();
     clockThread<span class="operator">.</span>wait();
     <span class="keyword">return</span> <span class="number">0</span>;
 }</pre>
<p>We've connected the <tt>clockThread</tt> with the label. The connection must be a queued signal-slot connection because we want to put the call in the event loop.</p>
<pre class="cpp"> <span class="comment">// clock/clockthread.h</span>
 <span class="keyword">class</span> ClockThread : <span class="keyword">public</span> <span class="type"><a href="qthread.html">QThread</a></span>
 {
     Q_OBJECT
 <span class="keyword">signals</span>:
     <span class="type">void</span> sendTime(<span class="type"><a href="qstring.html">QString</a></span> time);
 <span class="keyword">private</span>:
     <span class="type">void</span> run();
     <span class="type"><a href="qstring.html">QString</a></span> m_lastTime;
 <span class="keyword">private</span> <span class="keyword">slots</span>:
     <span class="type">void</span> timerHit();

 };</pre>
<p>We have derived a class from <a href="qthread.html">QThread</a> and declared the <tt>sendTime()</tt> signal.</p>
<pre class="cpp"> <span class="comment">// clock/clockthread.cpp</span>
 <span class="type">void</span> ClockThread<span class="operator">::</span>run()
 {
     <span class="type"><a href="qtimer.html">QTimer</a></span> timer;
     connect(<span class="operator">&amp;</span>timer<span class="operator">,</span> SIGNAL(timeout())<span class="operator">,</span> <span class="keyword">this</span><span class="operator">,</span> SLOT(timerHit())<span class="operator">,</span> <span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>DirectConnection);
     timer<span class="operator">.</span>setInterval(<span class="number">10</span>);
     timer<span class="operator">.</span>start();   <span class="comment">// puts one event in the threads event queue</span>
     exec();
     timer<span class="operator">.</span>stop();
 }

 <span class="type">void</span> ClockThread<span class="operator">::</span>timerHit()
 {
     <span class="type"><a href="qstring.html">QString</a></span> newTime<span class="operator">=</span> <span class="type"><a href="qdatetime.html">QDateTime</a></span><span class="operator">::</span>currentDateTime()<span class="operator">.</span>toString(<span class="string">&quot;ddd MMMM d yy, hh:mm:ss&quot;</span>);
     <span class="keyword">if</span>(m_lastTime <span class="operator">!</span><span class="operator">=</span> newTime ){
         m_lastTime <span class="operator">=</span> newTime;
         <span class="keyword">emit</span> sendTime(newTime) ;
     }
 }</pre>
<p>The trickiest part of this example is that the timer is connected to its slot via a direct connection. A default connection would produce a queued signal-slot connection because the connected objects live in different threads; remember that <a href="qthread.html">QThread</a> does not live in the thread it creates.</p>
<p>Still it is safe to access ClockThread::timerHit() from the worker thread because ClockThread::timerHit() is private and only touches local variables and a private member that isn't touched by public methods. <a href="qdatetime.html#currentDateTime">QDateTime::currentDateTime</a>() isn't marked as thread-safe in Qt documentation, however we can get away with using it in this small example because we know that the <a href="qdatetime.html#currentDateTime">QDateTime::currentDateTime</a>() static method isn't used in any other threads.</p>
<a name="example-4-a-permanent-thread"></a>
<h3>Example 4: A Permanent Thread</h3>
<p>This example shows how it is possible to have a <a href="qobject.html">QObject</a> in a worker thread that accepts requests from the GUI thread, does polling using a timer and continuously reports results back to the GUI thread. The actual work including the polling must be implemented in a class derived from <a href="qobject.html">QObject</a>. We have called this class <tt>WorkerObject</tt> in the code shown below. The thread-specific code is hidden in a class called <tt>Thread</tt>, derived from <a href="qthread.html">QThread</a>. <tt>Thread</tt> has two additional public members. The <tt>launchWorker()</tt> member takes the worker object and moves it to another thread with a started event loop. The call blocks for a very short moment until the thread creation operation is completed, allowing the worker object to be used again on the next line. The <tt>Thread</tt> class's code is short but somewhat involved, so we only show how to use the class.</p>
<pre class="cpp"> <span class="comment">// movedobject/main.cpp</span>
 <span class="type">int</span> main(<span class="type">int</span> argc<span class="operator">,</span> <span class="type">char</span> <span class="operator">*</span>argv<span class="operator">[</span><span class="operator">]</span>)
 {
     <span class="type"><a href="qcoreapplication.html">QCoreApplication</a></span> app(argc<span class="operator">,</span> argv);
     Thread thread;
     <a href="qtglobal.html#qDebug">qDebug</a>() <span class="operator">&lt;</span><span class="operator">&lt;</span> <span class="string">&quot;main thread ID: &quot;</span> <span class="operator">&lt;</span><span class="operator">&lt;</span> app<span class="operator">.</span>thread()<span class="operator">-</span><span class="operator">&gt;</span>currentThreadId();
     WorkerObject <span class="operator">*</span>worker <span class="operator">=</span> <span class="keyword">new</span> WorkerObject;
     thread<span class="operator">.</span>launchWorker(worker);
     <span class="type"><a href="qmetaobject.html">QMetaObject</a></span><span class="operator">::</span>invokeMethod(worker<span class="operator">,</span> <span class="string">&quot;doWork&quot;</span><span class="operator">,</span> <span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>QueuedConnection);
     <span class="type"><a href="qmetaobject.html">QMetaObject</a></span><span class="operator">::</span>invokeMethod(worker<span class="operator">,</span> <span class="string">&quot;startPolling&quot;</span><span class="operator">,</span>  <span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>QueuedConnection<span class="operator">,</span>  Q_ARG(<span class="type">int</span><span class="operator">,</span> <span class="number">500</span>));
     <span class="comment">//let application produce output for 3 seconds and quit</span>
     <span class="type"><a href="qtimer.html">QTimer</a></span><span class="operator">::</span>singleShot(<span class="number">3000</span><span class="operator">,</span> <span class="operator">&amp;</span>app<span class="operator">,</span> SLOT(quit()));
     app<span class="operator">.</span>exec();
     thread<span class="operator">.</span>stop();
     thread<span class="operator">.</span>wait();
     <span class="keyword">delete</span> worker;
     <span class="keyword">return</span> <span class="number">0</span>;
 }</pre>
<p><a href="qmetaobject.html#invokeMethod">QMetaObject::invokeMethod</a>() calls a slot via the event loop. The worker object's methods should not be called directly after the object has been moved to another thread. We let the worker thread do some work and polling, and use a timer to shut the application down after 3 seconds. Shutting the worker down needs some care. We call <tt>Thread::stop()</tt> to exit the event loop. We wait for the thread to terminate and, after this has occurred, we delete the worker.</p>
<a name="digging-deeper"></a>
<h2>Digging Deeper</h2>
<p>Threading is a very complicated subject. Qt offers more classes for threading than we have presented in this tutorial. The following materials can help you go into the subject in more depth:</p>
<ul>
<li>Good video tutorials about threads with Qt can be found in the material from the Training Day at Qt Developer Days 2009.</li>
<li>The <a href="threads.html">Thread Support in Qt</a> document is a good starting point into the reference documentation.</li>
<li>Qt comes with several additional examples for <a href="examples-threadandconcurrent.html">QThread and QtConcurrent</a>.</li>
<li>Several good books describe how to work with Qt threads. The most extensive coverage can be found in <i>Advanced Qt Programming</i> by Mark Summerfield, Prentice Hall - roughly 70 of 500 pages cover <a href="qthread.html">QThread</a> and <a href="qtconcurrent.html">QtConcurrent</a>.</li>
</ul>
</div>
<!-- @@@thread-basics.html -->
<p class="naviNextPrevious footerNavi">
</p>
      </div>
    </div>
    </div> 
    <div class="ft">
      <span></span>
    </div>
  </div> 
  <div class="footer">
    <p>
      <acronym title="Copyright">&copy;</acronym> 2015 The Qt Company Ltd.
      Documentation contributions included herein are the copyrights of
      their respective owners.</p>
    <br />
    <p>
      The documentation provided herein is licensed under the terms of the
      <a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation
      License version 1.3</a> as published by the Free Software Foundation.</p>
    <p>
      Documentation sources may be obtained from <a href="http://www.qt-project.org">
      www.qt-project.org</a>.</p>
    <br />
    <p>
      Qt and respective logos are trademarks of The Qt Company Ltd 
      in Finland and/or other countries worldwide. All other trademarks are property
      of their respective owners. <a title="Privacy Policy"
      href="http://en.gitorious.org/privacy_policy/">Privacy Policy</a></p>
  </div>

  <script src="scripts/functions.js" type="text/javascript"></script>
</body>
</html>