Sophie

Sophie

distrib > Mandriva > 2010.0 > i586 > media > contrib-release > by-pkgid > bad97183153701b09df5fae1052b1c30 > files > 4332

crystalspace-doc-1.2.1-5mdv2010.0.i586.rpm

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html401/loose.dtd">
<html>
<!-- Created by texi2html 1.76 -->
<!--
Written by: Lionel Cons <Lionel.Cons@cern.ch> (original author)
            Karl Berry  <karl@freefriends.org>
            Olaf Bachmann <obachman@mathematik.uni-kl.de>
            and many others.
Maintained by: Many creative people <dev@texi2html.cvshome.org>
Send bugs and suggestions to <users@texi2html.cvshome.org>

-->
<head>
<title>Crystal Space 1.2.1: 4.6.2.2 Threading library</title>

<meta name="description" content="Crystal Space 1.2.1: 4.6.2.2 Threading library">
<meta name="keywords" content="Crystal Space 1.2.1: 4.6.2.2 Threading library">
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="texi2html 1.76">
<meta http-equiv="Content-Type" content="text/html; charset=us-ascii">
<style type="text/css">
<!--
a.summary-letter {text-decoration: none}
pre.display {font-family: serif}
pre.format {font-family: serif}
pre.menu-comment {font-family: serif}
pre.menu-preformatted {font-family: serif}
pre.smalldisplay {font-family: serif; font-size: smaller}
pre.smallexample {font-size: smaller}
pre.smallformat {font-family: serif; font-size: smaller}
pre.smalllisp {font-size: smaller}
span.sansserif {font-family:sans-serif; font-weight:normal;}
ul.toc {list-style: none}
-->
</style>


</head>

<body lang="en" bgcolor="#FFFFFF" text="#000000" link="#0000FF" vlink="#800080" alink="#FF0000">

<a name="Threading"></a>
<a name="0"></a>
<table cellpadding="1" cellspacing="1" border="0">
<tr><td valign="middle" align="left">[<a href="Typed-Arrays.html#0" title="Previous section in reading order"> &lt; </a>]</td>
<td valign="middle" align="left">[<a href="VFS.html#0" title="Next section in reading order"> &gt; </a>]</td>
<td valign="middle" align="left"> &nbsp; </td>
<td valign="middle" align="left">[<a href="Using-Crystal-Space.html#0" title="Beginning of this chapter or previous chapter"> &lt;&lt; </a>]</td>
<td valign="middle" align="left">[<a href="csUtil.html#0" title="Up section"> Up </a>]</td>
<td valign="middle" align="left">[<a href="Working-with-Engine-Content.html#0" title="Next chapter"> &gt;&gt; </a>]</td>
<td valign="middle" align="left"> &nbsp; </td>
<td valign="middle" align="left"> &nbsp; </td>
<td valign="middle" align="left"> &nbsp; </td>
<td valign="middle" align="left"> &nbsp; </td>
<td valign="middle" align="left">[<a href="index.html#SEC_Top" title="Cover (top) of document">Top</a>]</td>
<td valign="middle" align="left">[<a href="cs_toc.html#SEC_Contents" title="Table of contents">Contents</a>]</td>
<td valign="middle" align="left">[<a href="cs_Index.html#0" title="Index">Index</a>]</td>
<td valign="middle" align="left">[<a href="cs_abt.html#SEC_About" title="About (help)"> ? </a>]</td>
</tr></table>
<hr size="1">
<h4 class="subsubsection"> 4.6.2.2 Threading library </h4>

<p>The threading library is a collection of routines and classes for creating
multithreaded and thread safe code and programs.
</p>
<p>Remember that just because you can make something multithreaded and threading
safe does not mean you should do so, or doing so is a good idea and will give
you a lot of benefit. Use with care, when appropriate.
</p>
<p>All threading related classes and operations are in the <code>CS::Threading</code>
namespace.
</p>
<a name="1"></a>
<h4 class="subsubheading"> Atomic operations </h4>
<p>Atomic operations are the basic and smallest operations behind threading safe
code. Atomic in this context means that they are guaranteed to complete with a
deterministic result in relation to other threads and even cores doing other
atomic operations on the same data.
</p>
<p>Atomic operations in Crystal Space is found in <code>CS::Threading::AtomicOperations</code>
class in <tt>&lsquo;csutil/threading/atomicops.h&rsquo;</tt>. There are a few different atomic
operations, namely:
</p>
<table>
<tr><td><p> Operation </p></td><td><p> Function </p></td><td><p> Description
</p></td></tr>
<tr><td><p> Set
</p></td><td><p> <code>AtomicOperations::Set</code>
</p></td><td><p> Atomically set the content of a pointer or 32 bit integer variable and 
return the value it had before setting it.
</p>
</td></tr>
<tr><td><p> Read
</p></td><td><p> <code>AtomicOperations::Read</code>
</p></td><td><p> Read content of pointer or 32 bit integer variable.
</p>
</td></tr>
<tr><td><p> Compare and Set (CAS)
</p></td><td><p> <code>AtomicOperations::CompareAndSet</code>
</p></td><td><p> Atomically compare current content of pointer or 32 bit integer variable
and if it is equal to a given value exchange it. Returns the value of the
variable before comparison.
Atomic CAS operations are among the most used and most useful when it comes to
building locking primitives or lock-free data structures.
</p>
</td></tr>
<tr><td><p> Increment
</p></td><td><p> <code>AtomicOperations::Increment</code>
</p></td><td><p> Atomically increment 32 bit integer variable and return its value prior
to incrementation.
</p>
</td></tr>
<tr><td><p> Decrement
</p></td><td><p> <code>AtomicOperations::Decrement</code>
</p></td><td><p> Atomically decrement 32 bit integer variable and return its value prior
to decrementation.
</p></td></tr>
</table>


<a name="2"></a>
<h4 class="subsubheading"> Threads </h4>
<p>A thread is the smallest unit of execution when looking at multithreaded
execution. Each thread is a &quot;lane&quot; of sequential execution and by having multiple
threads executing at the same time you get the effect of simultaneous 
execution.
</p>
<p>As this concept of simultaneous execution can be a bit confusing at first there
are two important things to remember
</p>
<ol>
<li>
The operating system have full control over how and when threads are executed.
This means that you can never be certain of if two threads are executed on
same or different processors or cores if you have dual processor/core system,
you cannot rely on different threads executing a specific order.

<p>A more important result of this is that you cannot rely on or even know when
one thread is interrupted to let another one execute. This means that whenever
you operate on data shared between two or more threads you must use one of the
syncronization primitives or atomic operations.
</p>
</li><li>
Threading is not always the answer. Wisely used in the correct cases it can 
provide a significant speedup and/or make the code easier, however in the wrong
spots it can make the code buggy, slow and complicated. Use with care!
</li></ol>

<p>To create a thread you first need to implement the interface 
<code>CS::Threading::Runnable</code> and instance it. Then create an instance of
<code>CS::Threading::Thread</code> to start a new thread executing the runnable
instance.
</p>
<p>Use the <code>Start()</code> and <code>Stop()</code> methods of the thread to control its
execution and <code>Wait()</code> to wait until it finishes execution.
</p>
<p>Here is an example of a simple thread and creation
</p>
<table><tr><td>&nbsp;</td><td><pre class="example">#include &quot;crystalspace.h&quot;

using namespace CS::Threading;

class MyRunner : public Runnable
{
  void Run ()
  {
    int i = 0;
    while (i &lt; 100)
    {
      // Wait for a while
      csSleep (1000);
      
      // Print a message. Notice that this is potentially not thread safe!
      csPrintf (&quot;Thread printing\n&quot;);
    }
  }
};

int main (int argc, char* argv[])
{
  // Instance runnable and thread
  csRef&lt;Runnable&gt; r; r.AttachNew (new MyRunner);
  csRef&lt;Thread&gt; thread; thread.AttachNew (new Thread (r));
  
  // Start the thread
  thread-&gt;Start ();
  
  // Wait for a while to let it run
  csSleep (500);
  
  // Wait for the thread to finish running
  thread-&gt;Wait ();
}
</pre></td></tr></table>
<p>As you can see in this example it is not doing anything useful while the thread
is running. In a real application you would do something useful while the thread
is for example waiting for IO.
</p>
<a name="3"></a>
<h4 class="subsubheading"> Syncronization primitives </h4>
<p>The threading library provides two different thread syncronization primitives.
The two works differently and do not have the same purpose. Which primitive
to use depends on the situation at hand.
</p>
<table>
<tr><td><p> Type </p></td><td><p> Class </p></td><td><p> Usage
</p>
</td></tr>
<tr><td><p> Mutex
</p></td><td><p> <code>Mutex</code>
</p></td><td><p> Mutually exclusive access to a shared resource. N threads share a common
buffer and only one thread should be allowed to modify it at a time.
</p>
</td></tr>
<tr><td><p> Condition
</p></td><td><p> <code>Condition</code>
</p></td><td><p> Signal that a condition is fullfilled. One or more threads wait for a 
condition to be signaled by a source.
</p></td></tr>
</table>

<p>To note is that a condition always is used together with a mutex, which also
should be shared between the threads.
</p>
<p>The example below shows how a mutex and a condition can be used to distribute
work units between two threads. Note, this sample works but is not fully complete.
For a better implementation, look at <code>CS::Threading::ThreadedJobQueue</code>
</p>
<table><tr><td>&nbsp;</td><td><pre class="example">#include &quot;crystalspace.h&quot;

using namespace CS::Threading;

// Shared data
csFIFO&lt;int&gt; queue;

// Mutex to protect it
Mutex queueMutex;
Condition newItemInQueue;


class MyRunner : Runnable
{
  void Run ()
  {
    while (true)
    {
      // Get an item from queue
      int myData;
      
      {
        // Make sure we lock the queue before trying to access it
        MutexScopedLock lock (queueMutex);
		
        // Wait until we have an item
        while (queue.Length() == 0)
          newItemInQueue.Wait (queueMutex);
		  
        // When we get here we know that:
        // 1. newItemInQueue have been signaled
        // 2. We have the queueMutex locked
        // 3. The queue is not empty
        
        // Get the data
        myData = queue.PopTop ();
      }
      
      // Process it
      csPrintf (&quot;Processing data: %d\n&quot;, myData);
      csSleep (400);
    }
  }
};

int main (int argc, char* argv[])
{
  // Instance runnable and thread
  csRef&lt;Runnable&gt; r; r.AttachNew (new MyRunner);
  csRef&lt;Thread&gt; thread; thread.AttachNew (new Thread (r));
  
  // Start the thread
  thread-&gt;Start ();
  
  // Give it some data
  for (int i = 0; i &lt; 100; ++i)
  {
    // Prepare the data
    int myData = (i * 10 + 31)  % 47;
    
    {
      //Lock the queue and insert our data
      MutexScopedLock lock (queueMutex);
      queue.Push (myData);
    }
    
    // Notify one waiting threads, let them compete over who takes it
    newItemInQueue.NotifyOne ();
  }
  
  ...
}

</pre></td></tr></table>



<hr size="1">
<table cellpadding="1" cellspacing="1" border="0">
<tr><td valign="middle" align="left">[<a href="Typed-Arrays.html#0" title="Previous section in reading order"> &lt; </a>]</td>
<td valign="middle" align="left">[<a href="VFS.html#0" title="Next section in reading order"> &gt; </a>]</td>
<td valign="middle" align="left"> &nbsp; </td>
<td valign="middle" align="left">[<a href="Using-Crystal-Space.html#0" title="Beginning of this chapter or previous chapter"> &lt;&lt; </a>]</td>
<td valign="middle" align="left">[<a href="csUtil.html#0" title="Up section"> Up </a>]</td>
<td valign="middle" align="left">[<a href="Working-with-Engine-Content.html#0" title="Next chapter"> &gt;&gt; </a>]</td>
<td valign="middle" align="left"> &nbsp; </td>
<td valign="middle" align="left"> &nbsp; </td>
<td valign="middle" align="left"> &nbsp; </td>
<td valign="middle" align="left"> &nbsp; </td>
<td valign="middle" align="left">[<a href="index.html#SEC_Top" title="Cover (top) of document">Top</a>]</td>
<td valign="middle" align="left">[<a href="cs_toc.html#SEC_Contents" title="Table of contents">Contents</a>]</td>
<td valign="middle" align="left">[<a href="cs_Index.html#0" title="Index">Index</a>]</td>
<td valign="middle" align="left">[<a href="cs_abt.html#SEC_About" title="About (help)"> ? </a>]</td>
</tr></table>
<p>
 <font size="-1">
  This document was generated using <a href="http://texi2html.cvshome.org/"><em>texi2html 1.76</em></a>.
 </font>
 <br>

</p>
</body>
</html>