Sophie

Sophie

distrib > Mageia > 6 > armv5tl > media > core-updates > by-pkgid > 768f7d9f703884aa2562bf0a651086df > files > 777

qtbase5-doc-5.9.4-1.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" />
<!-- waitconditions.qdoc -->
  <title>Wait Conditions Example | Qt Core 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 >Qt 5.9</td><td ><a href="qtcore-index.html">Qt Core</a></td><td >Wait Conditions Example</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">
<div class="sidebar">
<div class="toc">
<h3><a name="toc">Contents</a></h3>
<ul>
<li class="level1"><a href="#global-variables">Global Variables</a></li>
<li class="level1"><a href="#producer-class">Producer Class</a></li>
<li class="level1"><a href="#consumer-class">Consumer Class</a></li>
<li class="level1"><a href="#the-main-function">The main() Function</a></li>
</ul>
</div>
<div class="sidebar-content" id="sidebar-content"></div></div>
<h1 class="title">Wait Conditions Example</h1>
<span class="subtitle"></span>
<!-- $$$threads/waitconditions-description -->
<div class="descr"> <a name="details"></a>
<p>The producer writes data to the buffer until it reaches the end of the buffer, at which point it restarts from the beginning, overwriting existing data. The consumer thread reads the data as it is produced and writes it to standard error.</p>
<p>Wait conditions make it possible to have a higher level of concurrency than what is possible with mutexes alone. If accesses to the buffer were simply guarded by a <a href="qmutex.html">QMutex</a>, the consumer thread couldn't access the buffer at the same time as the producer thread. Yet, there is no harm in having both threads working on <i>different parts</i> of the buffer at the same time.</p>
<p>The example comprises two classes: <code>Producer</code> and <code>Consumer</code>. Both inherit from <a href="qthread.html">QThread</a>. The circular buffer used for communicating between these two classes and the synchronization tools that protect it are global variables.</p>
<p>An alternative to using <a href="qwaitcondition.html">QWaitCondition</a> and <a href="qmutex.html">QMutex</a> to solve the producer-consumer problem is to use <a href="qsemaphore.html">QSemaphore</a>. This is what the <a href="qtcore-threads-semaphores-example.html">Semaphores Example</a> does.</p>
<a name="global-variables"></a>
<h2 id="global-variables">Global Variables</h2>
<p>Let's start by reviewing the circular buffer and the associated synchronization tools:</p>
<pre class="cpp">

  <span class="keyword">const</span> <span class="type">int</span> DataSize <span class="operator">=</span> <span class="number">100000</span>;

  <span class="keyword">const</span> <span class="type">int</span> BufferSize <span class="operator">=</span> <span class="number">8192</span>;
  <span class="type">char</span> buffer<span class="operator">[</span>BufferSize<span class="operator">]</span>;

  <span class="type"><a href="qwaitcondition.html">QWaitCondition</a></span> bufferNotEmpty;
  <span class="type"><a href="qwaitcondition.html">QWaitCondition</a></span> bufferNotFull;
  <span class="type"><a href="qmutex.html">QMutex</a></span> mutex;
  <span class="type">int</span> numUsedBytes <span class="operator">=</span> <span class="number">0</span>;

</pre>
<p><code>DataSize</code> is the amount of data that the producer will generate. To keep the example as simple as possible, we make it a constant. <code>BufferSize</code> is the size of the circular buffer. It is less than <code>DataSize</code>, meaning that at some point the producer will reach the end of the buffer and restart from the beginning.</p>
<p>To synchronize the producer and the consumer, we need two wait conditions and one mutex. The <code>bufferNotEmpty</code> condition is signalled when the producer has generated some data, telling the consumer that it can start reading it. The <code>bufferNotFull</code> condition is signalled when the consumer has read some data, telling the producer that it can generate more. The <code>numUsedBytes</code> is the number of bytes in the buffer that contain data.</p>
<p>Together, the wait conditions, the mutex, and the <code>numUsedBytes</code> counter ensure that the producer is never more than <code>BufferSize</code> bytes ahead of the consumer, and that the consumer never reads data that the producer hasn't generated yet.</p>
<a name="producer-class"></a>
<h2 id="producer-class">Producer Class</h2>
<p>Let's review the code for the <code>Producer</code> class:</p>
<pre class="cpp">

  <span class="keyword">class</span> Producer : <span class="keyword">public</span> <span class="type"><a href="qthread.html">QThread</a></span>
  {
  <span class="keyword">public</span>:
      Producer(<span class="type"><a href="qobject.html">QObject</a></span> <span class="operator">*</span>parent <span class="operator">=</span> NULL) : <span class="type"><a href="qthread.html">QThread</a></span>(parent)
      {
      }

      <span class="type">void</span> run() override
      {
          qsrand(<span class="type"><a href="qtime.html">QTime</a></span>(<span class="number">0</span><span class="operator">,</span><span class="number">0</span><span class="operator">,</span><span class="number">0</span>)<span class="operator">.</span>secsTo(<span class="type"><a href="qtime.html">QTime</a></span><span class="operator">::</span>currentTime()));

          <span class="keyword">for</span> (<span class="type">int</span> i <span class="operator">=</span> <span class="number">0</span>; i <span class="operator">&lt;</span> DataSize; <span class="operator">+</span><span class="operator">+</span>i) {
              mutex<span class="operator">.</span>lock();
              <span class="keyword">if</span> (numUsedBytes <span class="operator">=</span><span class="operator">=</span> BufferSize)
                  bufferNotFull<span class="operator">.</span>wait(<span class="operator">&amp;</span>mutex);
              mutex<span class="operator">.</span>unlock();

              buffer<span class="operator">[</span>i <span class="operator">%</span> BufferSize<span class="operator">]</span> <span class="operator">=</span> <span class="string">&quot;ACGT&quot;</span><span class="operator">[</span>(<span class="type">int</span>)qrand() <span class="operator">%</span> <span class="number">4</span><span class="operator">]</span>;

              mutex<span class="operator">.</span>lock();
              <span class="operator">+</span><span class="operator">+</span>numUsedBytes;
              bufferNotEmpty<span class="operator">.</span>wakeAll();
              mutex<span class="operator">.</span>unlock();
          }
      }
  };

</pre>
<p>The producer generates <code>DataSize</code> bytes of data. Before it writes a byte to the circular buffer, it must first check whether the buffer is full (i.e&#x2e;, <code>numUsedBytes</code> equals <code>BufferSize</code>). If the buffer is full, the thread waits on the <code>bufferNotFull</code> condition.</p>
<p>At the end, the producer increments <code>numUsedBytes</code> and signalls that the condition <code>bufferNotEmpty</code> is true, since <code>numUsedBytes</code> is necessarily greater than 0.</p>
<p>We guard all accesses to the <code>numUsedBytes</code> variable with a mutex. In addition, the <a href="qwaitcondition.html#wait">QWaitCondition::wait</a>() function accepts a mutex as its argument. This mutex is unlocked before the thread is put to sleep and locked when the thread wakes up. Furthermore, the transition from the locked state to the wait state is atomic, to prevent race conditions from occurring.</p>
<a name="consumer-class"></a>
<h2 id="consumer-class">Consumer Class</h2>
<p>Let's turn to the <code>Consumer</code> class:</p>
<pre class="cpp">

  <span class="keyword">class</span> Consumer : <span class="keyword">public</span> <span class="type"><a href="qthread.html">QThread</a></span>
  {
      Q_OBJECT
  <span class="keyword">public</span>:
      Consumer(<span class="type"><a href="qobject.html">QObject</a></span> <span class="operator">*</span>parent <span class="operator">=</span> NULL) : <span class="type"><a href="qthread.html">QThread</a></span>(parent)
      {
      }

      <span class="type">void</span> run() override
      {
          <span class="keyword">for</span> (<span class="type">int</span> i <span class="operator">=</span> <span class="number">0</span>; i <span class="operator">&lt;</span> DataSize; <span class="operator">+</span><span class="operator">+</span>i) {
              mutex<span class="operator">.</span>lock();
              <span class="keyword">if</span> (numUsedBytes <span class="operator">=</span><span class="operator">=</span> <span class="number">0</span>)
                  bufferNotEmpty<span class="operator">.</span>wait(<span class="operator">&amp;</span>mutex);
              mutex<span class="operator">.</span>unlock();

              fprintf(stderr<span class="operator">,</span> <span class="string">&quot;%c&quot;</span><span class="operator">,</span> buffer<span class="operator">[</span>i <span class="operator">%</span> BufferSize<span class="operator">]</span>);

              mutex<span class="operator">.</span>lock();
              <span class="operator">-</span><span class="operator">-</span>numUsedBytes;
              bufferNotFull<span class="operator">.</span>wakeAll();
              mutex<span class="operator">.</span>unlock();
          }
          fprintf(stderr<span class="operator">,</span> <span class="string">&quot;\n&quot;</span>);
      }

  <span class="keyword">signals</span>:
      <span class="type">void</span> stringConsumed(<span class="keyword">const</span> <span class="type"><a href="qstring.html">QString</a></span> <span class="operator">&amp;</span>text);
  };

</pre>
<p>The code is very similar to the producer. Before we read the byte, we check whether the buffer is empty (<code>numUsedBytes</code> is 0) instead of whether it's full and wait on the <code>bufferNotEmpty</code> condition if it's empty. After we've read the byte, we decrement <code>numUsedBytes</code> (instead of incrementing it), and we signal the <code>bufferNotFull</code> condition (instead of the <code>bufferNotEmpty</code> condition).</p>
<a name="the-main-function"></a>
<h2 id="the-main-function">The main() Function</h2>
<p>In <code>main()</code>, we create the two threads and call <a href="qthread.html#wait">QThread::wait</a>() to ensure that both threads get time to finish before we exit:</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);
      Producer producer;
      Consumer consumer;
      producer<span class="operator">.</span>start();
      consumer<span class="operator">.</span>start();
      producer<span class="operator">.</span>wait();
      consumer<span class="operator">.</span>wait();
      <span class="keyword">return</span> <span class="number">0</span>;
  }

</pre>
<p>So what happens when we run the program? Initially, the producer thread is the only one that can do anything; the consumer is blocked waiting for the <code>bufferNotEmpty</code> condition to be signalled (<code>numUsedBytes</code> is 0). Once the producer has put one byte in the buffer, <code>numUsedBytes</code> is <code>BufferSize</code> - 1 and the <code>bufferNotEmpty</code> condition is signalled. At that point, two things can happen: Either the consumer thread takes over and reads that byte, or the producer gets to produce a second byte.</p>
<p>The producer-consumer model presented in this example makes it possible to write highly concurrent multithreaded applications. On a multiprocessor machine, the program is potentially up to twice as fast as the equivalent mutex-based program, since the two threads can be active at the same time on different parts of the buffer.</p>
<p>Be aware though that these benefits aren't always realized. Locking and unlocking a <a href="qmutex.html">QMutex</a> has a cost. In practice, it would probably be worthwhile to divide the buffer into chunks and to operate on chunks instead of individual bytes. The buffer size is also a parameter that must be selected carefully, based on experimentation.</p>
<p>Files:</p>
<ul>
<li><a href="qtcore-threads-waitconditions-waitconditions-cpp.html">threads/waitconditions/waitconditions.cpp</a></li>
<li><a href="qtcore-threads-waitconditions-waitconditions-pro.html">threads/waitconditions/waitconditions.pro</a></li>
</ul>
</div>
<!-- @@@threads/waitconditions -->
        </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>