<html>
<head>
<title>firstworks   Programming with Rudiments using the thread class</title>
<link href="../css/styles.css" rel="stylesheet">
</head>
<body>

<span class="heading">Using the thread class</span><br><br>

<ul>
<li><a href="#intro">Introduction</a></li>
<li><a href="#ordinary">Ordinary Threads</a></li>
<li><a href="#detach">Detached Threads</a></li>
</ul>

<br>
<a name="intro"></a>
<h3>Introduction</h3>

<p>The <a href="../classes/html/classthread.html">thread class</a> provides a simple thread implementation.</p>

<p>In this implementation, each instance of the thread class corresponds to a separate thread.  The setFunction() method associates a function with the thread.  When the run() method is called, a new thread is created, and the function is run in the new thread.  An optional argument may be passed to the function via the run() method.  This argument is usually used to pass a pointer to a class or struct, providing parameters for the thread function.</p>

<p>In these examples, two threads are spawned.  Each runs a separate instance of a "count" function which counts from 0 to some number and prints out the numbers.  Each thread is passed in a structure containing a pointer to the thread class, a thread id and a maximum number to count to.  The threads are not synchronized in any way, so the numbers will be printed out in seemingly random blocks.</p>

<p>Note that rudiments supports platforms that don't support threads, and it is possible to explicitly compile rudiments without thread support.  The supportsThreads() method returns true or false, indicating whether thread support is enabled or not.</p>

<br>
<a name="ordinary"></a>
<h3>Ordinary Threads</h3>

<p>Ordinarily, a thread runs until its function returns, or calls the exit() method.  Another thread (usually the main thread of the parent process) must call the join() method to completely dispose of the thread (analagous to "waiting on a child process") and get its exit status.</p> 

<blockquote class="code">
@thread-join.cpp.html@
</blockquote>

<br>
<a name="detach"></a>
<h3>Detached Threads</h3>

<p>Alternatively, a thread may dissociate itself from the parent by calling the detach() method.  In this case, the thread is completely disposed of when its function returns.  The parent process will only exit when all threads have exited.  Note that if a thread calls detach(), there is no way for it to return an exit status.</p>

<blockquote class="code">
@thread-detach.cpp.html@
</blockquote>

</body>
</html>
