<html>
<head>
<base href="https://wiki.asterisk.org/wiki">
<link rel="stylesheet" href="/wiki/s/2041/1/7/_/styles/combined.css?spaceKey=TOP&forWysiwyg=true" type="text/css">
</head>
<body style="background: white;" bgcolor="white" class="email-body">
<div id="pageContent">
<div id="notificationFormat">
<div class="wiki-content">
<div class="email">
<h2><s>Thread Pools</s></h2>
<h4>Page <b>removed</b> by <a href="https://wiki.asterisk.org/wiki/display/~mmichelson">Mark Michelson</a>
</h4>
<br/>
<div class="notificationGreySide">
<div class='panelMacro'><table class='warningMacro'><colgroup><col width='24'><col></colgroup><tr><td valign='top'><img src="/wiki/images/icons/emoticons/forbidden.gif" width="16" height="16" align="absmiddle" alt="" border="0"></td><td>Under construction<br/>
This page is likely to be deleted since new requirements/methods have come to light since this page was originally writ.</td></tr></table></div>
<p>Based on content from <a href="/wiki/display/TOP/Component+Threading+Design+for+Asynchronous+Operations" title="Component Threading Design for Asynchronous Operations">Component Threading Design for Asynchronous Operations</a>, the <tt>Workqueue</tt> interface and a subclass, <tt>SimpleWorkQueue</tt>, were created. While the <tt>SimpleWorkQueue</tt> is a good method for asynchronously queuing tasks, it only uses a single thread of execution. This page works to define a method for asynchronously assigning tasks to multiple threads. This pattern is referred to as a thread pool throughout the document.</p>
<h1><a name="ThreadPools-Configurationconsiderations"></a>Configuration considerations</h1>
<p>Thread pools have a potential for lots of knobs to be tweaked regarding their operation.</p>
<h3><a name="ThreadPools-StaticorDynamic"></a>Static or Dynamic</h3>
<p>A static thread pool is one in which a set number of threads are created at the time that the thread pool is constructed. The thread pool will always have this number of worker threads no matter the amount of system load. Dynamic thread pools start with some initial number of threads and then can grow or shrink depending on the amount of load on the system. Since static thread pools are simple, we will focus on the dynamic thread pool configuration.</p>
<h3><a name="ThreadPools-GrowthPolicy"></a>Growth Policy</h3>
<p>It's obvious that a dynamic thread pool should grow when needed, but there needs to be some set of rules to govern the growth. </p>
<h5><a name="ThreadPools-MaxSize"></a>Max Size</h5>
<p>One valid concern is letting the thread pool grow to an unreasonable size, so an obvious configuration option for dynamic thread pools is a maximum size. Once the thread pool has reached its maximum capacity it will no longer grow, even if load conditions would otherwise have triggered such growth.</p>
<h5><a name="ThreadPools-GrowthConditions"></a>Growth Conditions</h5>
<p>What also needs to be configurable is the determination of when to increase the size of the thread pool. System load is the typical metric used, and it can be determined in several ways, including</p>
<ul>
        <li>Frequency of tasks being queued</li>
        <li>Ratio of frequency of tasks being queued to frequency of tasks being completed</li>
        <li>Number of tasks currently queued</li>
        <li>Turnaround time of task execution (i.e. timestamp when task completes minus timestamp when task is queued)</li>
</ul>
<h5><a name="ThreadPools-Growthamount"></a>Growth amount</h5>
<p>Once it's been decided that the thread pool should grow, by how many threads should the pool grow? Common methods include growing by a fixed amount or doubling the size of the thread pool.</p>
<h3><a name="ThreadPools-ShrinkingPolicy"></a>Shrinking Policy</h3>
<p>A dynamic thread pool may grow as needed, but should the thread pool shrink if the system load has decreased? It certainly seems like it would be desired. Otherwise a spike in load could cause a permanent allocation of threads which would barely ever be used.</p>
<h5><a name="ThreadPools-MinSize"></a>Min Size</h5>
<p>It's useful to be able to shrink the thread pool, but it is also wise to make sure the thread pool doesn't get <b>too</b> small. Specifying a minimum size will allow for the thread pool to shrink only to a specified minimum.</p>
<h5><a name="ThreadPools-ShrinkConditions"></a>Shrink Conditions</h5>
<p>Like with growth, it needs to be determined what metric should be used to determine when a thread pool may shrink. Determining inactivity in a thread can really only be done by measuring the time that a thread has been idle. After a certain cutoff point, the thread can be considered "dead" and be removed from the pool. Unlike with thread pool growth, you can't really have a configured shrink amount since the pool must shrink a single thread at a time.</p>
<h3><a name="ThreadPools-Initialsize"></a>Initial size</h3>
<p>Both dynamic and static thread pools will need an initial size. The static thread pool will just remain that size forever whereas the dynamic thread pool will adjust based on other parameters.</p>
<h3><a name="ThreadPools-Configurationconclusions"></a>Configuration conclusions</h3>
<p>The list certainly is not extensive enough to cover all potential needs of a thread pool. Each thread pool usage will have its own unique needs, so the best way to control thread pool behavior is not through configuration of the thread pool itself. Rather, a listener can make decisions based on current activity of the thread pool.</p>
<h1><a name="ThreadPools-Theinterface"></a>The interface</h1>
<p>Note that some liberties have been taken with regards to namespacing here. The intent should be obvious, though.</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<script type="syntaxhighlighter" class="toolbar: false; theme: Confluence; brush: java; gutter: false"><![CDATA[
/**
* A base class for receiving notifications
* from a WorkQueue
*/
class WorkQueueListener
{
public:
/**
* Notification that a task has been enqueued.
*/
virtual void taskEnqueued(const boost::shared_ptr<WorkGroupId> &workGroupId,
unsigned long taskId, const boost::shared_ptr<WorkQueue> &queue) = 0;
/**
* Notification that a task has finished executing.
* XXX This is not possible with the current implementation of WorkQueue
*/
virtual void taskCompleted(const boost::shared_ptr<WorkGroupId> &workGroupid,
unsigned long taskId, const boost::shared_ptr<WorkQueue> &queue) = 0;
protected:
// You can't construct one of these. You must use a subclass.
WorkQueueListener();
};
class ThreadPool : public WorkQueue
{
public:
/**
* Create thread pool with given listener and initial number of threads.
*
* It is perfectly valid for the listener to be 0 here. This indicates either a desire
* to control the ThreadPool from a source other than a listener or that the ThreadPool
* should be static.
*/
ThreadPool(const boost::shared_ptr<WorkQueueListener> listener, size_t initThreads);
//Overriding the WorkQueue methods
virtual void enqueue(WorkPtr &w, WorkGroupId id);
virtual boost::shared_ptr<WorkGroupId> enqueue(WorkPtr &w);
/**
* Get the number of threads currently in the thread pool
*/
size_t numThreads();
/**
* Get the number of queued tasks in the thread pool
*/
size_t numTasks();
/**
* Get the number of queued tasks belonging to a specific work group
* XXX The current implementation of SimpleWorkQueue prevents us
* from determining the exact number of tasks in a queue.
*/
size_t numTasks(const boost::shared_ptr<WorkGroupId> &id);
/**
* Set the number of threads in the thread pool to numThreads
* This method is used to grow or shrink a thread pool to a specific size.
*/
void setNumThreads(size_t numThreads);
//XXX More public methods may be necessary for the ThreadPoolListener to
//effectively gauge whether growth is necessary. Ideas welcome :)
private:
boost::shared_ptr<WorkQueueListener> mListener;
unsigned int mNumTasks;
};
]]></script>
</div></div>
<p>So first, let's have a look at <tt>ThreadPool</tt>. It is a subclass of <tt>WorkQueue</tt>, meaning that it overrides the methods to enqueue new tasks. In addition to the <tt>WorkQueue</tt> overrides, <tt>ThreadPool</tt> exposes methods to allow growth or shrinkage if desired. Note that the above code is meant to serve as an interface, not a specific implementation. For instance, the method of queuing and distributing tasks may vary between subclasses of <tt>ThreadPool</tt>, so such details are omitted here.</p>
<p>The <tt>WorkQueueListener</tt> is the more interesting part here. The <tt>WorkQueueListener</tt> is notified whenever tasks are enqueued or completed. This way, the <tt>WorkQueueListener</tt> can enact local policy and command the <tt>ThreadPool</tt> to grow or shrink if desired. It would be prudent to provide some <tt>WorkQueueListener}}s that implement common grow/shrink policies so that {{ThreadPool</tt> users will not always be forced to define their own policies.</p>
<h1><a name="ThreadPools-Prerequisites"></a>Prerequisites</h1>
<p>At this time, <tt>WorkQueues</tt> do not know about <tt>WorkQueueListeners</tt>. <tt>WorkQueue</tt> and its subclasses will need to be modified to take a <tt>WorkQueueListener</tt> as a constructor parameter.</p>
</div>
</div>
</div>
</div>
</div>
</body>
</html>