Sophie

Sophie

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

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" />
<!-- semaphores.qdoc -->
  <title>Semaphores 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 >Semaphores 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">Semaphores Example</h1>
<span class="subtitle"></span>
<!-- $$$threads/semaphores-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>Semaphores make it possible to have a higher level of concurrency than mutexes. If accesses to the buffer were 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 semaphores that protect it are global variables.</p>
<p>An alternative to using <a href="qsemaphore.html">QSemaphore</a> to solve the producer-consumer problem is to use <a href="qwaitcondition.html">QWaitCondition</a> and <a href="qmutex.html">QMutex</a>. This is what the <a href="qtcore-threads-waitconditions-example.html">Wait Conditions 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 semaphores:</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="qsemaphore.html">QSemaphore</a></span> freeBytes(BufferSize);
  <span class="type"><a href="qsemaphore.html">QSemaphore</a></span> usedBytes;

</pre>
<p><code>DataSize</code> is the amout 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 semaphores. The <code>freeBytes</code> semaphore controls the &quot;free&quot; area of the buffer (the area that the producer hasn't filled with data yet or that the consumer has already read). The <code>usedBytes</code> semaphore controls the &quot;used&quot; area of the buffer (the area that the producer has filled but that the consumer hasn't read yet).</p>
<p>Together, the semaphores 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>
<p>The <code>freeBytes</code> semaphore is initialized with <code>BufferSize</code>, because initially the entire buffer is empty. The <code>usedBytes</code> semaphore is initialized to 0 (the default value if none is specified).</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>:
      <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) {
              freeBytes<span class="operator">.</span>acquire();
              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>;
              usedBytes<span class="operator">.</span>release();
          }
      }
  };

</pre>
<p>The producer generates <code>DataSize</code> bytes of data. Before it writes a byte to the circular buffer, it must acquire a &quot;free&quot; byte using the <code>freeBytes</code> semaphore. The <a href="qsemaphore.html#acquire">QSemaphore::acquire</a>() call might block if the consumer hasn't kept up the pace with the producer.</p>
<p>At the end, the producer releases a byte using the <code>usedBytes</code> semaphore. The &quot;free&quot; byte has successfully been transformed into a &quot;used&quot; byte, ready to be read by the consumer.</p>
<a name="consumer-class"></a>
<h2 id="consumer-class">Consumer Class</h2>
<p>Let's now 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>:
      <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) {
              usedBytes<span class="operator">.</span>acquire();
              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>);
              freeBytes<span class="operator">.</span>release();
          }
          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);

  <span class="keyword">protected</span>:
      bool finish;
  };

</pre>
<p>The code is very similar to the producer, except that this time we acquire a &quot;used&quot; byte and release a &quot;free&quot; byte, instead of the opposite.</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>usedBytes</code> semaphore to be released (its initial <a href="qsemaphore.html#available">available()</a> count is 0). Once the producer has put one byte in the buffer, <code>freeBytes.available()</code> is <code>BufferSize</code> - 1 and <code>usedBytes.available()</code> is 1. At that point, two things can happen: Either the consumer thread takes over and reads that byte, or the producer thread 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. Acquiring and releasing a <a href="qsemaphore.html">QSemaphore</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-semaphores-semaphores-cpp.html">threads/semaphores/semaphores.cpp</a></li>
<li><a href="qtcore-threads-semaphores-semaphores-pro.html">threads/semaphores/semaphores.pro</a></li>
</ul>
</div>
<!-- @@@threads/semaphores -->
        </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>