Sophie

Sophie

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

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: Threads and QObjects</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>Threads and QObjects</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="prev" href="threads-reentrancy.html" />
  <link rel="next" href="threads-qtconcurrent.html" />
<p class="naviNextPrevious headerNavi">
<a class="prevPage" href="threads-reentrancy.html">Reentrancy and Thread-Safety</a>
<a class="nextPage" href="threads-qtconcurrent.html">Concurrent Programming</a>
</p><p/>
<div class="toc">
<h3><a name="toc">Contents</a></h3>
<ul>
<li class="level1"><a href="#qobject-reentrancy">QObject Reentrancy</a></li>
<li class="level1"><a href="#per-thread-event-loop">Per-Thread Event Loop</a></li>
<li class="level1"><a href="#accessing-qobject-subclasses-from-other-threads">Accessing QObject Subclasses from Other Threads</a></li>
<li class="level1"><a href="#signals-and-slots-across-threads">Signals and Slots Across Threads</a></li>
</ul>
</div>
<h1 class="title">Threads and QObjects</h1>
<span class="subtitle"></span>
<!-- $$$threads-qobject.html-description -->
<div class="descr"> <a name="details"></a>
<p><a href="qthread.html">QThread</a> inherits <a href="qobject.html">QObject</a>. It emits signals to indicate that the thread started or finished executing, and provides a few slots as well.</p>
<p>More interesting is that <a href="qobject.html">QObject</a>s can be used in multiple threads, emit signals that invoke slots in other threads, and post events to objects that &quot;live&quot; in other threads. This is possible because each thread is allowed to have its own event loop.</p>
<a name="qobject-reentrancy"></a>
<h2>QObject Reentrancy</h2>
<p><a href="qobject.html">QObject</a> is reentrant. Most of its non-GUI subclasses, such as <a href="qtimer.html">QTimer</a>, <a href="qtcpsocket.html">QTcpSocket</a>, <a href="qudpsocket.html">QUdpSocket</a>, <a href="qftp.html">QFtp</a>, and <a href="qprocess.html">QProcess</a>, are also reentrant, making it possible to use these classes from multiple threads simultaneously. Note that these classes are designed to be created and used from within a single thread; creating an object in one thread and calling its functions from another thread is not guaranteed to work. There are three constraints to be aware of:</p>
<ul>
<li><i>The child of a <a href="qobject.html">QObject</a> must always be created in the thread where the parent was created.</i> This implies, among other things, that you should never pass the <a href="qthread.html">QThread</a> object (<tt>this</tt>) as the parent of an object created in the thread (since the <a href="qthread.html">QThread</a> object itself was created in another thread).</li>
<li><i>Event driven objects may only be used in a single thread.</i> Specifically, this applies to the <a href="timers.html">timer mechanism</a> and the <a href="qtnetwork.html">network module</a>. For example, you cannot start a timer or connect a socket in a thread that is not the <a href="qobject.html#thread">object's thread</a>.</li>
<li><i>You must ensure that all objects created in a thread are deleted before you delete the <a href="qthread.html">QThread</a>.</i> This can be done easily by creating the objects on the stack in your <a href="qthread.html#run">run()</a> implementation.</li>
</ul>
<p>Although <a href="qobject.html">QObject</a> is reentrant, the GUI classes, notably <a href="qwidget.html">QWidget</a> and all its subclasses, are not reentrant. They can only be used from the main thread. As noted earlier, <a href="qcoreapplication.html#exec">QCoreApplication::exec</a>() must also be called from that thread.</p>
<p>In practice, the impossibility of using GUI classes in other threads than the main thread can easily be worked around by putting time-consuming operations in a separate worker thread and displaying the results on screen in the main thread when the worker thread is finished. This is the approach used for implementing the <a href="threads-mandelbrot.html">Mandelbrot</a> and the <a href="network-blockingfortuneclient.html">Blocking Fortune Client</a> example.</p>
<a name="per-thread-event-loop"></a>
<h2>Per-Thread Event Loop</h2>
<p>Each thread can have its own event loop. The initial thread starts its event loops using <a href="qcoreapplication.html#exec">QCoreApplication::exec</a>(); other threads can start an event loop using <a href="qthread.html#exec">QThread::exec</a>(). Like <a href="qcoreapplication.html">QCoreApplication</a>, <a href="qthread.html">QThread</a> provides an <a href="qthread.html#exit">exit</a>(int) function and a <a href="qthread.html#quit">quit()</a> slot.</p>
<p>An event loop in a thread makes it possible for the thread to use certain non-GUI Qt classes that require the presence of an event loop (such as <a href="qtimer.html">QTimer</a>, <a href="qtcpsocket.html">QTcpSocket</a>, and <a href="qprocess.html">QProcess</a>). It also makes it possible to connect signals from any threads to slots of a specific thread. This is explained in more detail in the <a href="#signals-and-slots-across-threads">Signals and Slots Across Threads</a> section below.</p>
<p class="centerAlign"><img src="images/threadsandobjects.png" alt="Threads, objects, and event loops" /></p><p>A <a href="qobject.html">QObject</a> instance is said to <i>live</i> in the thread in which it is created. Events to that object are dispatched by that thread's event loop. The thread in which a <a href="qobject.html">QObject</a> lives is available using <a href="qobject.html#thread">QObject::thread</a>().</p>
<p>Note that for <a href="qtwebkit-bridge.html#qobjects">QObjects</a> that are created before <a href="qapplication.html">QApplication</a>, <a href="qobject.html#thread">QObject::thread</a>() returns zero. This means that the main thread will only handle posted events for these objects; other event processing is not done at all for objects with no thread. Use the <a href="qobject.html#moveToThread">QObject::moveToThread</a>() function to change the thread affinity for an object and its children (the object cannot be moved if it has a parent).</p>
<p>Calling <tt>delete</tt> on a <a href="qobject.html">QObject</a> from a thread other than the one that <i>owns</i> the object (or accessing the object in other ways) is unsafe, unless you guarantee that the object isn't processing events at that moment. Use <a href="qobject.html#deleteLater">QObject::deleteLater</a>() instead, and a <a href="qevent.html#Type-enum">DeferredDelete</a> event will be posted, which the event loop of the object's thread will eventually pick up. By default, the thread that <i>owns</i> a <a href="qobject.html">QObject</a> is the thread that <i>creates</i> the <a href="qobject.html">QObject</a>, but not after <a href="qobject.html#moveToThread">QObject::moveToThread</a>() has been called.</p>
<p>If no event loop is running, events won't be delivered to the object. For example, if you create a <a href="qtimer.html">QTimer</a> object in a thread but never call <a href="qthread.html#exec">exec()</a>, the <a href="qtimer.html">QTimer</a> will never emit its <a href="qtimer.html#timeout">timeout()</a> signal. Calling <a href="qobject.html#deleteLater">deleteLater()</a> won't work either. (These restrictions apply to the main thread as well.)</p>
<p>You can manually post events to any object in any thread at any time using the thread-safe function <a href="qcoreapplication.html#postEvent">QCoreApplication::postEvent</a>(). The events will automatically be dispatched by the event loop of the thread where the object was created.</p>
<p>Event filters are supported in all threads, with the restriction that the monitoring object must live in the same thread as the monitored object. Similarly, <a href="qcoreapplication.html#sendEvent">QCoreApplication::sendEvent</a>() (unlike <a href="qcoreapplication.html#postEvent">postEvent()</a>) can only be used to dispatch events to objects living in the thread from which the function is called.</p>
<a name="accessing-qobject-subclasses-from-other-threads"></a>
<h2>Accessing QObject Subclasses from Other Threads</h2>
<p><a href="qobject.html">QObject</a> and all of its subclasses are not thread-safe. This includes the entire event delivery system. It is important to keep in mind that the event loop may be delivering events to your <a href="qobject.html">QObject</a> subclass while you are accessing the object from another thread.</p>
<p>If you are calling a function on an <a href="qobject.html">QObject</a> subclass that doesn't live in the current thread and the object might receive events, you must protect all access to your <a href="qobject.html">QObject</a> subclass's internal data with a mutex; otherwise, you may experience crashes or other undesired behavior.</p>
<p>Like other objects, <a href="qthread.html">QThread</a> objects live in the thread where the object was created -- <i>not</i> in the thread that is created when <a href="qthread.html#run">QThread::run</a>() is called. It is generally unsafe to provide slots in your <a href="qthread.html">QThread</a> subclass, unless you protect the member variables with a mutex.</p>
<p>On the other hand, you can safely emit signals from your <a href="qthread.html#run">QThread::run</a>() implementation, because signal emission is thread-safe.</p>
<a name="signals-and-slots-across-threads"></a>
<h2>Signals and Slots Across Threads</h2>
<p>Qt supports these signal-slot connection types:</p>
<ul>
<li><a href="qt.html#ConnectionType-enum">Auto Connection</a> (default) If the signal is emitted in the thread which the receiving object has affinity then the behavior is the same as the Direct Connection. Otherwise, the behavior is the same as the Queued Connection.&quot;</li>
<li><a href="qt.html#ConnectionType-enum">Direct Connection</a> The slot is invoked immediately, when the signal is emitted. The slot is executed in the emitter's thread, which is not necessarily the receiver's thread.</li>
<li><a href="qt.html#ConnectionType-enum">Queued Connection</a> The slot is invoked when control returns to the event loop of the receiver's thread. The slot is executed in the receiver's thread.</li>
<li><a href="qt.html#ConnectionType-enum">Blocking Queued Connection</a> The slot is invoked as for the Queued Connection, except the current thread blocks until the slot returns. <b>Note:</b> Using this type to connect objects in the same thread will cause deadlock.</li>
<li><a href="qt.html#ConnectionType-enum">Unique Connection</a> The behavior is the same as the Auto Connection, but the connection is made only if it does not duplicate an existing connection. i.e&#x2e;, if the same signal is already connected to the same slot for the same pair of objects, then the connection is not made and connect() returns false.</li>
</ul>
<p>The connection type can be specified by passing an additional argument to <a href="qobject.html#connect">connect()</a>. Be aware that using direct connections when the sender and receiver live in different threads is unsafe if an event loop is running in the receiver's thread, for the same reason that calling any function on an object living in another thread is unsafe.</p>
<p><a href="qobject.html#connect">QObject::connect</a>() itself is thread-safe.</p>
<p>The <a href="threads-mandelbrot.html">Mandelbrot</a> example uses a queued connection to communicate between a worker thread and the main thread. To avoid freezing the main thread's event loop (and, as a consequence, the application's user interface), all the Mandelbrot fractal computation is done in a separate worker thread. The thread emits a signal when it is done rendering the fractal.</p>
<p>Similarly, the <a href="network-blockingfortuneclient.html">Blocking Fortune Client</a> example uses a separate thread for communicating with a TCP server asynchronously.</p>
</div>
<!-- @@@threads-qobject.html -->
<p class="naviNextPrevious footerNavi">
<a class="prevPage" href="threads-reentrancy.html">Reentrancy and Thread-Safety</a>
<a class="nextPage" href="threads-qtconcurrent.html">Concurrent Programming</a>
</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>