Sophie

Sophie

distrib > Mageia > 6 > i586 > by-pkgid > f93881942bd3805980c2fe63aa853d78 > files > 274

qtdoc5-5.9.4-1.mga6.noarch.rpm

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- threads.qdoc -->
  <title>Multithreading Technologies in Qt | Qt 5.9</title>
  <link rel="stylesheet" type="text/css" href="style/offline-simple.css" />
  <script type="text/javascript">
    document.getElementsByTagName("link").item(0).setAttribute("href", "style/offline.css");
    // loading style sheet breaks anchors that were jumped to before
    // so force jumping to anchor again
    setTimeout(function() {
        var anchor = location.hash;
        // need to jump to different anchor first (e.g. none)
        location.hash = "#";
        setTimeout(function() {
            location.hash = anchor;
        }, 0);
    }, 0);
  </script>
</head>
<body>
<div class="header" id="qtdocheader">
  <div class="main">
    <div class="main-rounded">
      <div class="navigationbar">
        <table><tr>
<td ><a href="index.html">Qt 5.9</a></td><td >Multithreading Technologies in Qt</td></tr></table><table class="buildversion"><tr>
<td id="buildversion" width="100%" align="right">Qt 5.9.4 Reference Documentation</td>
        </tr></table>
      </div>
    </div>
<div class="content">
<div class="line">
<div class="content mainContent">
  <link rel="prev" href="threads.html" />
  <link rel="next" href="threads-synchronizing.html" />
<p class="naviNextPrevious headerNavi">
<a class="prevPage" href="threads.html">Thread Support in Qt</a>
<span class="naviSeparator">  &#9702;  </span>
<a class="nextPage" href="threads-synchronizing.html">Synchronizing Threads</a>
</p><p/>
<div class="sidebar">
<div class="toc">
<h3><a name="toc">Contents</a></h3>
<ul>
<li class="level1"><a href="#qthread-low-level-api-with-optional-event-loops">QThread: Low-Level API with Optional Event Loops</a></li>
<li class="level1"><a href="#qthreadpool-and-qrunnable-reusing-threads">QThreadPool and QRunnable: Reusing Threads</a></li>
<li class="level1"><a href="#qt-concurrent-using-a-high-level-api">Qt Concurrent: Using a High-level API</a></li>
<li class="level1"><a href="#workerscript-threading-in-qml">WorkerScript: Threading in QML</a></li>
<li class="level1"><a href="#choosing-an-appropriate-approach">Choosing an Appropriate Approach</a></li>
<li class="level2"><a href="#comparison-of-solutions">Comparison of Solutions</a></li>
<li class="level2"><a href="#example-use-cases">Example Use Cases</a></li>
</ul>
</div>
<div class="sidebar-content" id="sidebar-content"></div></div>
<h1 class="title">Multithreading Technologies in Qt</h1>
<span class="subtitle"></span>
<!-- $$$threads-technologies.html-description -->
<div class="descr"> <a name="details"></a>
<p>Qt offers many classes and functions for working with threads. Below are four different approaches that Qt programmers can use to implement multithreaded applications.</p>
<a name="qthread-low-level-api-with-optional-event-loops"></a>
<h2 id="qthread-low-level-api-with-optional-event-loops">QThread: Low-Level API with Optional Event Loops</h2>
<p>QThread is the foundation of all thread control in Qt. Each QThread instance represents and controls one thread.</p>
<p>QThread can either be instantiated directly or subclassed. Instantiating a QThread provides a parallel event loop, allowing QObject slots to be invoked in a secondary thread. Subclassing a QThread allows the application to initialize the new thread before starting its event loop, or to run parallel code without an event loop.</p>
<p>See the QThread class reference and the <a href="examples-threadandconcurrent.html">threading examples</a> for demonstrations on how to use QThread.</p>
<a name="qthreadpool-and-qrunnable-reusing-threads"></a>
<h2 id="qthreadpool-and-qrunnable-reusing-threads">QThreadPool and QRunnable: Reusing Threads</h2>
<p>Creating and destroying threads frequently can be expensive. To reduce this overhead, existing threads can be reused for new tasks. QThreadPool is a collection of reuseable QThreads.</p>
<p>To run code in one of a QThreadPool's threads, reimplement QRunnable::run() and instantiate the subclassed QRunnable. Use QThreadPool::start() to put the QRunnable in the QThreadPool's run queue. When a thread becomes available, the code within QRunnable::run() will execute in that thread.</p>
<p>Each Qt application has a global thread pool, which is accessible through QThreadPool::globalInstance(). This global thread pool automatically maintains an optimal number of threads based on the number of cores in the CPU. However, a separate QThreadPool can be created and managed explicitly.</p>
<a name="qt-concurrent-using-a-high-level-api"></a>
<h2 id="qt-concurrent-using-a-high-level-api">Qt Concurrent: Using a High-level API</h2>
<p>The Qt Concurrent module provides high-level functions that deal with some common parallel computation patterns: map, filter, and reduce. Unlike using QThread and QRunnable, these functions never require the use of <a href="threads-synchronizing.html#low-level-synchronization-primitives">low-level threading primitives</a> such as mutexes or semaphores. Instead, they return a QFuture object which can be used to retrieve the functions' results when they are ready. QFuture can also be used to query computation progress and to pause/resume/cancel the computation. For convenience, QFutureWatcher enables interactions with QFutures via signals and slots.</p>
<p>Qt Concurrent's map, filter and reduce algorithms automatically distribute computation across all available processor cores, so applications written today will continue to scale when deployed later on a system with more cores.</p>
<p>This module also provides the QtConcurrent::run() function, which can run any function in another thread. However, QtConcurrent::run() only supports a subset of features available to the map, filter and reduce functions. The QFuture can be used to retrieve the function's return value and to check if the thread is running. However, a call to QtConcurrent::run() uses one thread only, cannot be paused/resumed/canceled, and cannot be queried for progress.</p>
<p>See the Qt Concurrent module documentation for details on the individual functions.</p>
<a name="workerscript-threading-in-qml"></a>
<h2 id="workerscript-threading-in-qml">WorkerScript: Threading in QML</h2>
<p>The WorkerScript QML type lets JavaScript code run in parallel with the GUI thread.</p>
<p>Each WorkerScript instance can have one <code>.js</code> script attached to it. When WorkerScript::sendMessage() is called, the script will run in a separate thread (and a separate QML context). When the script finishes running, it can send a reply back to the GUI thread which will invoke the WorkerScript::onMessage() signal handler.</p>
<p>Using a WorkerScript is similar to using a worker QObject that has been moved to another thread. Data is transferred between threads via signals.</p>
<p>See the WorkerScript documentation for details on how to implement the script, and for a list of data types that can be passed between threads.</p>
<a name="choosing-an-appropriate-approach"></a>
<h2 id="choosing-an-appropriate-approach">Choosing an Appropriate Approach</h2>
<p>As demonstrated above, Qt provides different solutions for developing threaded applications. The right solution for a given application depends on the purpose of the new thread and the thread's lifetime. Below is a comparison of Qt's threading technologies, followed by recommended solutions for some example use cases.</p>
<a name="comparison-of-solutions"></a>
<h3 >Comparison of Solutions</h3>
<div class="table"><table class="generic">
 <thead><tr class="qt-style"><th >Feature</th><th >QThread</th><th >QRunnable and QThreadPool</th><th >QtConcurrent::run()</th><th >Qt Concurrent (Map, Filter, Reduce)</th><th >WorkerScript</th></tr></thead>
<tr valign="top" class="odd"><td >Language</td><td >C++</td><td >C++</td><td >C++</td><td >C++</td><td >QML</td></tr>
<tr valign="top" class="even"><td >Thread priority can be specified</td><td >Yes</td><td >Yes</td><td ></td><td ></td><td ></td></tr>
<tr valign="top" class="odd"><td >Thread can run an event loop</td><td >Yes</td><td ></td><td ></td><td ></td><td ></td></tr>
<tr valign="top" class="even"><td >Thread can receive data updates through signals</td><td >Yes (received by a worker QObject)</td><td ></td><td ></td><td ></td><td >Yes (received by WorkerScript)</td></tr>
<tr valign="top" class="odd"><td >Thread can be controlled using signals</td><td >Yes (received by QThread)</td><td ></td><td ></td><td >Yes (received by QFutureWatcher)</td><td ></td></tr>
<tr valign="top" class="even"><td >Thread can be monitored through a QFuture</td><td ></td><td ></td><td >Partially</td><td >Yes</td><td ></td></tr>
<tr valign="top" class="odd"><td >Built-in ability to pause/resume/cancel</td><td ></td><td ></td><td ></td><td >Yes</td><td ></td></tr>
</table></div>
<a name="example-use-cases"></a>
<h3 >Example Use Cases</h3>
<div class="table"><table class="generic">
 <thead><tr class="qt-style"><th >Lifetime of thread</th><th >Operation</th><th >Solution</th></tr></thead>
<tr valign="top" class="odd"><td >One call</td><td >Run a new linear function within another thread, optionally with progress updates during the run.</td><td >Qt provides different solutions:<ul>
<li>Place the function in a reimplementation of QThread::run() and start the QThread. Emit signals to update progress. OR</li>
<li>Place the function in a reimplementation of QRunnable::run() and add the QRunnable to a QThreadPool. Write to a <a href="threads-synchronizing.html">thread-safe variable</a> to update progress. OR</li>
<li>Run the function using QtConcurrent::run(). Write to a <a href="threads-synchronizing.html">thread-safe variable</a> to update progress.</li>
</ul>
</td></tr>
<tr valign="top" class="even"><td >One call</td><td >Run an existing function within another thread and get its return value.</td><td >Run the function using QtConcurrent::run(). Have a QFutureWatcher emit the finished() signal when the function has returned, and call QFutureWatcher::result() to get the function's return value.</td></tr>
<tr valign="top" class="odd"><td >One call</td><td >Perform an operation on all items of a container, using all available cores. For example, producing thumbnails from a list of images.</td><td >Use Qt Concurrent's QtConcurrent::filter() function to select container elements, and the QtConcurrent::map() function to apply an operation to each element. To fold the output into a single result, use QtConcurrent::filteredReduced() and QtConcurrent::mappedReduced() instead.</td></tr>
<tr valign="top" class="even"><td >One call/Permanent</td><td >Perfrom a long computation in a pure QML application, and update the GUI when the results are ready.</td><td >Place the computation code in a <code>.js</code> script and attach it to a WorkerScript instance. Call sendMessage() to start the computation in a new thread. Let the script call WorkerScript::sendMessage() too, to pass the result back to the GUI thread. Handle the result in <code>onMessage</code> and update the GUI there.</td></tr>
<tr valign="top" class="odd"><td >Permanent</td><td >Have an object living in another thread that can perform different tasks upon request and/or can receive new data to work with.</td><td >Subclass a QObject to create a worker. Instantiate this worker object and a QThread. Move the worker to the new thread. Send commands or data to the worker object over queued signal-slot connections.</td></tr>
<tr valign="top" class="even"><td >Permanent</td><td >Repeatedly perform an expensive operation in another thread, where the thread does not need to receive any signals or events.</td><td >Write the infinite loop directly within a reimplementation of QThread::run(). Start the thread without an event loop. Let the thread emit signals to send data back to the GUI thread.</td></tr>
</table></div>
</div>
<!-- @@@threads-technologies.html -->
<p class="naviNextPrevious footerNavi">
<a class="prevPage" href="threads.html">Thread Support in Qt</a>
<span class="naviSeparator">  &#9702;  </span>
<a class="nextPage" href="threads-synchronizing.html">Synchronizing Threads</a>
</p>
        </div>
       </div>
   </div>
   </div>
</div>
<div class="footer">
   <p>
   <acronym title="Copyright">&copy;</acronym> 2017 The Qt Company Ltd.
   Documentation contributions included herein are the copyrights of
   their respective owners.<br>    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.<br>    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. </p>
</div>
</body>
</html>