iocp thread pooling in c#by william kennedycontinuum technology centerintroduction
when building server based applications in c#, it is important to have the ability to create thread pools. thread pools allow our server to queue and perform work in the most efficient and scalable way possible. without thread pooling we are left with two options. the first option is to perform all of the work on a single thread. the second option is to spawn a thread every time some piece of work needs to be done. for this article, work is defined as an event that requires the processing of code. work may or may not be associated with data, and it is our job to process all of the work our server receives in the most efficient and fastest way possible.
as a general rule, if you can accomplish all of the work required with a single thread, then only use a single thread. having multiple threads performing work at the same time does not necessarily mean our application is getting more work done, or getting work done faster. this is true for many reasons.
for example, if you spawn multiple threads which attempt to access the same resource bound to a synchronization object, like a monitor object, these threads will serialize and fall in line waiting for the resource to become available. as each thread tries to access the resource, it has the potential to block, and wait for the thread that owns the resource to release the resource. at that point, these waiting threads are put to sleep, and not getting any work done. in fact, these waiting threads have caused more work for the operating system to perform. now the operating system must task another thread to perform work, and then determine which thread, waiting for the resource, may access the resource next, once it becomes available. if the threads that need to perform work are sleeping, because they are waiting for the resource to become available, we have actually created a performance problem. in this case it would be more efficient to queue up this work and have a single thread process the queue.
threads that start waiting for a resource before other threads, are not guaranteed to be given the resource first. in diagram a, thread 1 requests access to the resource before thread 2, and thread 2 requests access to the resource before thread 3. the operating system however decides to give the resource to thread 1 first, then thread 3, and then thread 2. this scenario causes work to be performed in an undetermined order. the possible issues are endless when dealing with multi-threaded applications.
if work received can be performed independent of each other, we could always spawn a thread for processing that piece of work. the problem here is that an operating system like windows has severe performance problems when a large number of threads are created or running at the same time, waiting to have access to the cpu. the windows operating system needs to manage all of these threads, and compared to the unix operating system, it just doesn’t hold up. if large amounts of work are issued to the server, this model will most likely cause the windows operating system to become overloaded. system performance will degrade drastically.
this article is a case study comparing thread performance between windows nt and solaris.
http://www.usenix.org/publications/library/proceedings/usenix-nt98/full_papers/zabatta/zabatta_html/zabatta.html
in the .net framework, the “system.threading” namespace has a threadpool class. unfortunately, it is a static class and therefore our server can only have a single thread pool. this isn’t the only issue. the threadpool class does not allow us to set the concurrency level of the thread pool. the concurrency level is the most important setting when configuring a thread pool. the concurrency level defines how many threads in the pool may be in an “active state” at the same time. if we set this parameter correctly, we will have the most efficient, performance enhanced thread pool for the work being processed.
imagine we have a thread pool with 4 threads and a concurrency level of 1. then, three pieces of work are queued up for processing in the pool. since the concurrency level for the thread pool is 1, only a single thread from the pool is activated and given work from the queue. even though there are two pieces of work queued up, no other threads are activated. this is because the concurrency level is set to 1. if the concurrency level was set to 2, then another thread would have been activated immediately and given work from the queue. in diagram b we have thread 1 running and all of the other threads sleeping with two pieces of work queued.
so the question exists, why have more than 1 thread in the pool if the concurrency level is set to 1? if thread 1 in diagram b ever goes to sleep before it completes its work, another thread from the pool will be activated. when thread 1 goes to sleep, there are 0 threads “active” in the pool and it is ok to activate a new thread based on the concurrency level. in diagram c, we now have thread 1 sleeping and thread 4 running with one piece of work queued.
eventually, thread 1 will wake up, and it is possible for thread 4 to still be active. we have 2 threads active in the pool, even though the concurrency level is set to 1. in diagram d, we now have thread 1 and thread 4 running and one piece of work still queued.
the last piece of work in the queue will need to wait until both threads return to a sleeping state. this is because the concurrency level is set to 1. as we can see, even though the concurrency level restricts the number of active threads in the pool at any given time, we could have more active threads then the concurrency level allows. it all depends on the state of the threads in the pool and how fast the threads can complete the work they are processing.
a good rule of thumb is to set the concurrency level to match the number of cpu’s in the system. if the machine our server is running on only has one cpu, then only one thread can be executing at any given time. it will require a task swap to have another thread get cpu time. we want to reduce the number of active threads at any given time to maximize performance. this also leads to scalability. as the number of cpu’s increase, we can increase the concurrency level because there is a cpu to execute that thread. this is a general rule and is always a good starting point for configuring our thread pools.
the bottom line is, if the cpu is available, and there is work to perform, activate a thread. if the cpu is not available, do not activate a thread. one other thing, we need to be careful that we don’t cause a situation where the threads in the pool are constantly being put to sleep for long periods of time during the processing of work. this may cause all of the threads in the pool to constantly be in an active state, defeating the efficiency of the pool and the performance of the server.
the remaining scope of this article will show you how to add iocp thread pools to your c# server based applications. how to configure the thread pools for your specific application will not be covered. it is suggested to use the general rules as discussed.
system requirements
a basic understanding of c# is required to follow through the examples and the classes. basic concepts of type, properties, threading, synchronization, and delegates are required.
defining the problem
iocp thread support has not been made available to c# developers through the “system.threading” namespace. we need to access the win32 api calls from the kernel32.dll. this requires us to write unsafe code. this is really not a problem, but something that needs to be discussed. let’s take a look at the win32 api calls we need to implement an iocp thread pool.
[dllimport("kernel32", charset=charset.auto)]
private unsafe static extern uint32 createiocompletionport(uint32 hfile, uint32 hexistingcompletionport, uint32* puicompletionkey, uint32 uinumberofconcurrentthreads);
this win32 api call is used to create an iocp thread pool. the first argument will always be set to invalid_handle_value, which is 0xffffffff. this tells the operating system this iocp thread pool is not linked to a device. the second argument will always be set to 0. there is no existing iocp thread pool because we are creating this for the first time. the third argument will always be null. we do not require a key because we have not associated this iocp thread pool with a device. the last argument is the important argument. here we define the concurrency level of the thread pool. if we pass a 0 for this argument the operating system will set the concurrency level to match the number of cpu’s in the machine. this option gives us our best chance to be scalable and take advantage of the number of cpu’s present in the machine. this api call will return a handle to the newly created iocp thread pool. if the api call fails, it will return null.
[dllimport("kernel32", charset=charset.auto)]
private unsafe static extern boolean closehandle(uint32 hobject);
this win32 api call is used to close our thread pool. the only argument is the handle to the iocp thread pool. this api call will return true or false if the handle can not be closed.
[dllimport("kernel32", charset=charset.auto)]
private unsafe static extern boolean postqueuedcompletionstatus(uint32 hcompletionport, uint32 uisizeofargument, uint32* puiuserarg, overlapped* poverlapped);
this win32 api call is used to post work in the iocp thread pool queue. other threads in our application will make this win32 api call. the first argument is the handle to the iocp thread pool. the second argument is the size of the data we are posting to the queue. the third argument is a value or a reference to an object or data structure we are posting to the queue. the last argument will always be null. the following diagram shows how the data is associated with the posted work.
in diagram e, we have two threads actively processing posted work and one piece of work on the queue waiting for its data to be processed. the thing to note here is that each piece of work was given a reference to its specific data. i am calling this variable pdata to help describe what is happening in the iocp thread pool. the actual name or structure of this variable is undocumented.
when we make this api call in a c++ application, we can pass the address of any object in memory we wish, as in diagram e. in c#, we don’t have the same luxury because of the managed heap. the managed heap is a contiguous region of address space that contains all of the memory allocated for reference variables. the heap maintains a pointer that indicates where the next object is to be allocated, and all allocations are contiguous from that point. this is much different from the c-runtime heap.
the c-runtime heap uses a link list of data structures to reference available memory blocks. for the c-runtime heap to allocate memory, it must walk through the link list until a large enough block of free memory is found. then the free block of memory must be resized, and the link list adjusted. if objects are allocated consecutively in a c++ application, those objects could be allocated anywhere on the heap. this can never happen with the managed heap. objects that are allocated consecutively in a c# application will always be allocated consecutively on the managed heap. the catch is that the managed heap must be compacted to guarantee the heap does not run out of memory. that is the job of garbage collection.
for more information on garbage collection, try these links:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconautomaticmemorymanagement.asp
http://msdn.microsoft.com/msdnmag/issues/1100/gci/default.aspx
http://msdn.microsoft.com/msdnmag/issues/1200/gci2/default.aspx
in diagram f, we have allocated four objects on the managed heap. imagine that the managed heap has allocated memory for these objects at address fdeo, fddo, fdco, and fdbo. this would mean the value of pclass1 is fdeo, the value of pclass2 is fddo, the value of pclass3 is fdco, and the value of pclass4 is fdbo.
myclass pclass1 = new myclass();
myclass pclass2 = new myclass();
myclass pclass3 = new myclass();
myclass pclass4 = new myclass();
now we write the following code.
pclass2 = null;
diagram g shows what happens to the managed heap after garbage collection takes place and the managed heap is compacted.
the class 2 object has been removed from the managed heap and the class3 and class 4 objects have been moved. now the value of pclass3 is fddo and the value of pclass4 is fdco. the value that the pointer points to has changed. the garbage collection process changes the values of all reference variables to make sure they are pointing to the correct objects after the managed heap is compacted.
so what does this mean for our iocp thread pool implementation? if we pass the reference of a managed object as the data for the work, there is a chance the reference is no longer valid when a thread in the pool is chosen to work on the data.
in diagram h, we have passed a reference to the class 3 object as the data for the work posted to the iocp thread pool. this object is at address fdco. before the work is given to thread 1, the class 2 object is marked for deletion. then the garbage collection process runs, and the managed heap is compacted. now in diagram i, the work has been given to thread 1 for processing. the value of pdata is still fdco, but class 3 is no longer at address fdco, it is at address fddo. the thread will perform the work, but using class 4 instead of class 3.
the garbage collection process can not change the value of pdata, as it does with other variables, because this variable is not a managed variable. it is a variable owned by the iocp thread pool and exists outside the scope of the clr. the garbage collector has no knowledge of this variable or access to this variable. the variable is set during the unsafe call to postqueuedcompletionstatus.
unfortunately, pinning the objects we want to pass as the data for the work posted to the iocp thread pool is not a possible solution. pinning provides the ability to prevent an object from being moved on the manage heap during the garbage collection process. we can not pin these objects because there is no way to pin an object in one thread and unpin the object in a different thread. to pin an object, we need to use the fixed keyword. this keyword can only be used in the context of a single method. here is a quick example of pinning.
int32 iarray = new int32[5] {12, 34, 56, 78, 90};
unsafe
{
fixed (int32* piarray = iarray)
{
// do something
}
}
the safest thing we can do is pass a value to the iocp thread pool. this value could be the index from a managed array, containing a reference to an object on the managed heap. if the garbage collection process does compact the heap, the index values of the array will not change. in diagram j and k, we can see one way to properly pass data for the work posted to the iocp thread pool. after the garbage collection process compacts the heap, the values of pdata change, but the index positions to the pdata variables do not change.
[dllimport("kernel32", charset=charset.auto)]
private static extern boolean getqueuedcompletionstatus(uint32 hcompletionport, uint32* psizeofargument, uint32* puiuserarg, overlapped** ppoverlapped, uint32 uimilliseconds);
the final win32 api call is used to add threads to the iocp thread pool. any thread that makes this win32 api call will become part of the iocp thread pool. this is a blocking call and the method will return when the iocp thread pool chooses the thread to perform work. the first argument is the handle to the iocp thread pool. the second argument is the size of the data associated with the work. this value was provided when the work was posted. the third argument is the data value or data reference associated with the work. this value was provided when the work was posted. the forth argument is the address to a pointer of type overlapped. this address is returned after the call. the last argument is the time in milliseconds the thread should wait to be activated to perform work. we will always pass infinite or 0xffffffff.
these are the win32 api calls we need to add iocp thread pool support to our c# server based applications. we need to encapsulate these win32 api calls using .net threads and minimize the sections of unsafe code. we need to prevent the application developer from passing a reference variable into the iocp thread pool, by restricting them to passing only integer values.
defining the solution
we will build a class that encapsulates a single iocp thread pool. the application developer will be able to instantiate as many thread pools as he wishes. during construction, the application developer will be able to: set the concurrency level of the thread pool, set the minimum and maximum number of threads in the pool, and will be able to provide a method to be called when work posted to the thread pool needs to be processed. the application developer will also be able to post work with data into the iocp thread pool.
component design and coding
start by adding a new class to your c# project. remove all of the code provided by the visual studio .net wizard. then add the following namespaces. the system.runtime.interopservices namespace is required to access the win32 api methods from the kernel32 dll.
using system;
using system.threading;
using system.runtime.interopservices;
don’t forget to change the project properties to allow unsafe code blocks. this can be done by opening the project properties and selecting the configuration properties. under the build / code generation section you will see “allow unsafe code blocks”. set this to true.
next add the namespace. you will notice that i have defined a two level namespace. this is great when you are building a class library with many different classes.
namespace continuum.threading
{
the postqueuedcompletionstatus and getqueuedcompletionstats win32 api methods both require a pointer to the win32 overlapped structure. because this structure will be used by the unsafe win32 api call, we need to make sure the structure is aligned exactly the same way it would be in our c++ applications. this can be accomplished by using the structlayout attribute. by setting the attribute to “layoutkind.sequential”, the structure will be aligned based on the same rules as the c++ compiler.
the structure requires members that are pointers. the only way to add pointers to this structure is to use the unsafe keyword. we can still use the fcl types when defining the structure. this is very important because we can make sure the structure is identical to the c++ version.
// structures
//=============================================================================
/// <summary> this is the win32 overlapped structure </summary>
[structlayout(layoutkind.sequential, charset=charset.auto)]
public unsafe struct overlapped
{
uint32* ulpinternal;
uint32* ulpinternalhigh;
int32 loffset;
int32 loffsethigh;
uint32 hevent;
}
now it is time to define the iocp thread pool class. i am using the keyword sealed in the definition of this class. the sealed keyword tells the compiler that this class can not be inherited. if you know there is no reason for a class to be inherited, use the sealed keyword. certain run-time optimizations are enabled for the class when the sealed keyword is used.
// classes
//=============================================================================
/// <summary> this class provides the ability to create a thread pool to manage work. the
/// class abstracts the win32 iocompletionport api so it requires the use of
/// unmanaged code. unfortunately the .net framework does not provide this functionality </summary>
public sealed class iocpthreadpool
{
the first section of the iocp thread pool class is the win32 function prototypes. these are the same ones described earlier.
// win32 function prototypes
/// <summary> win32func: create an io completion port thread pool </summary>
[dllimport("kernel32", charset=charset.auto)]
private unsafe static extern uint32 createiocompletionport(uint32 hfile, uint32 hexistingcompletionport, uint32* puicompletionkey, uint32 uinumberofconcurrentthreads);
/// <summary> win32func: closes an io completion port thread pool </summary>
[dllimport("kernel32", charset=charset.auto)]
private unsafe static extern boolean closehandle(uint32 hobject);
/// <summary> win32func: posts a context based event into an io completion port thread pool </summary>
[dllimport("kernel32", charset=charset.auto)]
private unsafe static extern boolean postqueuedcompletionstatus(uint32 hcompletionport, uint32 uisizeofargument, uint32* puiuserarg, overlapped* poverlapped);
/// <summary> win32func: waits on a context based event from an io completion port thread pool.
/// all threads in the pool wait in this win32 function </summary>
[dllimport("kernel32", charset=charset.auto)]
private unsafe static extern boolean getqueuedcompletionstatus(uint32 hcompletionport, uint32* psizeofargument, uint32* puiuserarg, overlapped** ppoverlapped, uint32 uimilliseconds);
the next section is the constants section. here we need to define the win32 constants required for the win32 api calls we are going to make later.
// constants
/// <summary> simtypeconst: this represents the win32 invalid handle value macro </summary>
private const uint32 invalid_handle_value = 0xffffffff;
/// <summary> simtypeconst: this represents the win32 infinite macro </summary>
private const uint32 inifinite = 0xffffffff;
/// <summary> simtypeconst: this tells the iocp function to shutdown </summary>
private const int32 shutdown_iocpthread = 0x7fffffff;
the delegate function type section is where we define any delegate functions. we need one delegate function type to define the signature of the function we will call when work needs to be processed.
// delegate function types
/// <summary> deltype: this is the type of user function to be supplied for the thread pool </summary>
public delegate void user_function(int32 ivalue);
these private properties are required to maintain the application developer’s settings. the most interesting property is the getuserfunction property. this property contains a reference to a method supplied by the application developer. we will use this property to call the application developers method.
// private properties
private uint32 m_hhandle;
/// <summary> simtype: contains the io completion port thread pool handle for this instance </summary>
private uint32 gethandle { get { return m_hhandle; } set { m_hhandle = value; } }
private int32 m_uimaxconcurrency;
/// <summary> simtype: the maximum number of threads that may be running at the same time </summary>
private int32 getmaxconcurrency { get { return m_uimaxconcurrency; } set { m_uimaxconcurrency = value; } }
private int32 m_iminthreadsinpool;
/// <summary> simtype: the minimal number of threads the thread pool maintains </summary>
private int32 getminthreadsinpool { get { return m_iminthreadsinpool; } set { m_iminthreadsinpool = value; } }
private int32 m_imaxthreadsinpool;
/// <summary> simtype: the maximum number of threads the thread pool maintains </summary>
private int32 getmaxthreadsinpool { get { return m_imaxthreadsinpool; } set { m_imaxthreadsinpool = value; } }
private object m_pcriticalsection;
/// <summary> reftype: a serialization object to protect the class state </summary>
private object getcriticalsection { get { return m_pcriticalsection; } set { m_pcriticalsection = value; } }
private user_function m_pfnuserfunction;
/// <summary> deltype: a reference to a user specified function to be call by the thread pool </summary>
private user_function getuserfunction { get { return m_pfnuserfunction; } set { m_pfnuserfunction = value; } }
private boolean m_bdisposeflag;
/// <summary> simtype: flag to indicate if the class is disposing </summary>
private boolean isdisposed { get { return m_bdisposeflag; } set { m_bdisposeflag = value; } }
these public properties are used to determine if new threads need to be added to the thread pool. these properties also provide statistical data about the thread pool. here we use the interlocked class to provide serialization when we increment or decrement these properties. this is the least expensive way to perform serialization.
// public properties
private int32 m_icurthreadsinpool;
/// <summary> simtype: the current number of threads in the thread pool </summary>
public int32 getcurthreadsinpool { get { return m_icurthreadsinpool; } set { m_icurthreadsinpool = value; } }
/// <summary> simtype: increment current number of threads in the thread pool </summary>
private int32 inccurthreadsinpool() { return interlocked.increment(ref m_icurthreadsinpool); }
/// <summary> simtype: decrement current number of threads in the thread pool </summary>
private int32 deccurthreadsinpool() { return interlocked.decrement(ref m_icurthreadsinpool); }
private int32 m_iactthreadsinpool;
/// <summary> simtype: the current number of active threads in the thread pool </summary>
public int32 getactthreadsinpool { get { return m_iactthreadsinpool; } set { m_iactthreadsinpool = value; } }
/// <summary> simtype: increment current number of active threads in the thread pool </summary>
private int32 incactthreadsinpool() { return interlocked.increment(ref m_iactthreadsinpool); }
/// <summary> simtype: decrement current number of active threads in the thread pool </summary>
private int32 decactthreadsinpool() { return interlocked.decrement(ref m_iactthreadsinpool); }
private int32 m_icurworkinpool;
/// <summary> simtype: the current number of work posted in the thread pool </summary>
public int32 getcurworkinpool { get { return m_icurworkinpool; } set { m_icurworkinpool = value; } }
/// <summary> simtype: increment current number of work posted in the thread pool </summary>
private int32 inccurworkinpool() { return interlocked.increment(ref m_icurworkinpool); }
/// <summary> simtype: decrement current number of work posted in the thread pool </summary>
private int32 deccurworkinpool() { return interlocked.decrement(ref m_icurworkinpool); }
the constructor method does several things. the class state is initialized and then the iocp thread pool is created with a call to the createiocompletionport method. notice the method call is within the scope of the unsafe keyword. this is required because we are passing pointers into the win32 api call. the last thing we do is create the minimal number of threads specified by the application developer. notice we use the .net threading classes to create the threads. we do not need to use the unsafe createthread method. one might think we need to because these threads will be calling the getqueuedcompletionstatus win32 api method.
// constructor, finalize, and dispose
//********************************************************************
/// <summary> constructor </summary>
/// <param name = "imaxconcurrency"> simtype: max number of running threads allowed </param>
/// <param name = "iminthreadsinpool"> simtype: min number of threads in the pool </param>
/// <param name = "imaxthreadsinpool"> simtype: max number of threads in the pool </param>
/// <param name = "pfnuserfunction"> deltype: reference to a function to call to perform work </param>
/// <exception cref = "exception"> unhandled exception </exception>
public iocpthreadpool(int32 imaxconcurrency, int32 iminthreadsinpool, int32 imaxthreadsinpool, user_function pfnuserfunction)
{
try
{
// set initial class state
getmaxconcurrency = imaxconcurrency;
getminthreadsinpool = iminthreadsinpool;
getmaxthreadsinpool = imaxthreadsinpool;
getuserfunction = pfnuserfunction;
// init the thread counters
getcurthreadsinpool = 0;
getactthreadsinpool = 0;
getcurworkinpool = 0;
// initialize the monitor object
getcriticalsection = new object();
// set the disposing flag to false
isdisposed = false;
unsafe
{
// create an io completion port for thread pool use
gethandle = createiocompletionport(invalid_handle_value, 0, null, (uint32) getmaxconcurrency);
}
// test to make sure the io completion port was created
if (gethandle == 0)
throw new exception("unable to create io completion port");
// allocate and start the minimum number of threads specified
int32 istartingcount = getcurthreadsinpool;
threadstart tsthread = new threadstart(iocpfunction);
for (int32 ithread = 0; ithread < getminthreadsinpool; ++ithread)
{
// create a thread and start it
thread ththread = new thread(tsthread);
ththread.name = "iocp " + ththread.gethashcode();
ththread.start();
// increment the thread pool count
inccurthreadsinpool();
}
}
catch
{
throw new exception("unhandled exception");
}
}
the finalize method is only required to guarantee the iocp thread pool handle is closed. as a general rule, if a class allocates a resource outside the scope of the .net framework, a finalize method is required else do not add a finalize method. a finalize method will cause the garbage collection process to spend more time trying to release the memory for the object.
//********************************************************************
/// <summary> finalize called by the gc </summary>
~iocpthreadpool()
{
if (!isdisposed)
dispose();
}
the dispose method will not return until all of the threads in the pool have been terminated. we can’t use the abort method to kill the threads in the pool because any thread blocked, via the call to the getqueuedcompletionstatus win32 api method, will not respond to the abort message. the getqueuedcompletionstatus win32 api method will cause the thread to run outside the scope of the clr and the .net framework will lose access to the thread. so what we do is post work into the iocp thread pool. we pass the shutdown_iocpthread data when we post the work. this will tell the thread to terminate. then, we wait in a spin lock, until all of the threads have terminated. the last thing is to close the iocp thread pool.
//********************************************************************
/// <summary> called when the object will be shutdown. this
/// function will wait for all of the work to be completed
/// inside the queue before completing </summary>
public void dispose()
{
try
{
// flag that we are disposing this object
isdisposed = true;
// get the current number of threads in the pool
int32 icurthreadsinpool = getcurthreadsinpool;
// shutdown all thread in the pool
for (int32 ithread = 0; ithread < icurthreadsinpool; ++ithread)
{
unsafe
{
bool bret = postqueuedcompletionstatus(gethandle, 4, (uint32*) shutdown_iocpthread, null);
}
}
// wait here until all the threads are gone
while (getcurthreadsinpool != 0) thread.sleep(100);
unsafe
{
// close the iocp handle
closehandle(gethandle);
}
}
catch
{
}
}
the only private method is the iocpfunction method. this method is spawned as a thread and is made part of the iocp thread pool by calling the getqueuedcompletionstatus win32 api method. when the getqueuedcompletionstatus win32 api method returns, we check to make sure we are not being asked to shutdown the thread. the third argument is the data associated with the posted work. if the data is not shutdown_iocpthread, then real work has been posted into the iocp thread pool and this thread has been chosen to process the work. the application developer’s supplied user function is called since the application developer is the only one who knows what needs to be done. once that is complete, the method checks if a new thread should be added to the pool. this is done by reviewing the number of active threads in the pool.
// private methods
//********************************************************************
/// <summary> iocp worker function that calls the specified user function </summary>
private void iocpfunction()
{
uint32 uinumberofbytes;
int32 ivalue;
try
{
while (true)
{
unsafe
{
overlapped* pov;
// wait for an event
getqueuedcompletionstatus(gethandle, &uinumberofbytes, (uint32*) &ivalue, &pov, inifinite);
}
// decrement the number of events in queue
deccurworkinpool();
// was this thread told to shutdown
if (ivalue == shutdown_iocpthread)
break;
// increment the number of active threads
incactthreadsinpool();
try
{
// call the user function
getuserfunction(ivalue);
}
catch
{
}
// get a lock
monitor.enter(getcriticalsection);
try
{
// if we have less than max threads currently in the pool
if (getcurthreadsinpool < getmaxthreadsinpool)
{
// should we add a new thread to the pool
if (getactthreadsinpool == getcurthreadsinpool)
{
if (isdisposed == false)
{
// create a thread and start it
threadstart tsthread = new threadstart(iocpfunction);
thread ththread = new thread(tsthread);
ththread.name = "iocp " + ththread.gethashcode();
ththread.start();
// increment the thread pool count
inccurthreadsinpool();
}
}
}
}
catch
{
}
// relase the lock
monitor.exit(getcriticalsection);
// increment the number of active threads
decactthreadsinpool();
}
}
catch
{
}
// decrement the thread pool count
deccurthreadsinpool();
}
the last two public methods are the postevent methods. the first method takes an integer as an argument and the second version takes no argument at all. the integer is the data the application developer wishes to pass with the work posted into the iocp thread pool. in the postqueuedcompletionstatus win32 api call, we can see that the third argument is where we pass the data value. since this value is always an integer we set the size of the data to four, as seen in the second argument. like in the iocpfunction, we check to see if we need to add a new thread to the pool.
// public methods
//********************************************************************
/// <summary> iocp worker function that calls the specified user function </summary>
/// <param name="ivalue"> simtype: a value to be passed with the event </param>
/// <exception cref = "exception"> unhandled exception </exception>
public void postevent(int32 ivalue)
{
try
{
// only add work if we are not disposing
if (isdisposed == false)
{
unsafe
{
// post an event into the iocp thread pool
postqueuedcompletionstatus(gethandle, 4, (uint32*) ivalue, null);
}
// increment the number of item of work
inccurworkinpool();
// get a lock
monitor.enter(getcriticalsection);
try
{
// if we have less than max threads currently in the pool
if (getcurthreadsinpool < getmaxthreadsinpool)
{
// should we add a new thread to the pool
if (getactthreadsinpool == getcurthreadsinpool)
{
if (isdisposed == false)
{
// create a thread and start it
threadstart tsthread = new threadstart(iocpfunction);
thread ththread = new thread(tsthread);
ththread.name = "iocp " + ththread.gethashcode();
ththread.start();
// increment the thread pool count
inccurthreadsinpool();
}
}
}
}
catch
{
}
// release the lock
monitor.exit(getcriticalsection);
}
}
catch (exception e)
{
throw e;
}
catch
{
throw new exception("unhandled exception");
}
}
//********************************************************************
/// <summary> iocp worker function that calls the specified user function </summary>
/// <exception cref = "exception"> unhandled exception </exception>
public void postevent()
{
try
{
// only add work if we are not disposing
if (isdisposed == false)
{
unsafe
{
// post an event into the iocp thread pool
postqueuedcompletionstatus(gethandle, 0, null, null);
}
// increment the number of item of work
inccurworkinpool();
// get a lock
monitor.enter(getcriticalsection);
try
{
// if we have less than max threads currently in the pool
if (getcurthreadsinpool < getmaxthreadsinpool)
{
// should we add a new thread to the pool
if (getactthreadsinpool == getcurthreadsinpool)
{
if (isdisposed == false)
{
// create a thread and start it
threadstart tsthread = new threadstart(iocpfunction);
thread ththread = new thread(tsthread);
ththread.name = "iocp " + ththread.gethashcode();
ththread.start();
// increment the thread pool count
inccurthreadsinpool();
}
}
}
}
catch
{
}
// release the lock
monitor.exit(getcriticalsection);
}
}
catch (exception e)
{
throw e;
}
catch
{
throw new exception("unhandled exception");
}
}
}
}
we have now completed the implementation of the iocp thread pool class. now it is time to test it.
the sample application
start by adding a new class to your c# project. remove all of the code provided by the visual studio .net wizard. then add all of the following code. in
main
, an iocp thread pool is created, and a single piece of work is posted to the iocp thread pool. we pass the data value of 10 along with the posted work. the main thread is then put to sleep. this gives the iocp thread function time to wake up to process the work posted. the last thing in main is to dispose the iocp thread pool. the iocp thread function displays the value of the data passed into the iocp thread pool.
using system;
using system.threading; // included for the thread.sleep call
using continuum.threading;
namespace sample
{
//=============================================================================
/// <summary> sample class for the threading class </summary>
public class utilthreadingsample
{
//*****************************************************************************
/// <summary> test method </summary>
static void
main
()
{
// create the mssql iocp thread pool
iocpthreadpool pthreadpool = new iocpthreadpool(0, 5, 10, new iocpthreadpool.user_function(iocpthreadfunction));
pthreadpool.postevent(10);
thread.sleep(100);
pthreadpool.dispose();
}
//********************************************************************
/// <summary> function to be called by the iocp thread pool. called when
/// a command is posted for processing by the socketmanager </summary>
/// <param name="ivalue"> the value provided by the thread posting the event </param>
static public void iocpthreadfunction(int32 ivalue)
{
try
{
console.writeline("value: {0}", ivalue);
}
catch (exception pexception)
{
console.writeline(pexception.message);
}
}
}
}
this is what you should see when you run the sample application. on your own change the main function to call the postevent method several times and see how the iocp thread pool performs.
review
this class provides the iocp thread pooling support your server based software requires. by using this class, you can build efficient and robust servers that can scale as the amount of work increases. though there are some limitations due to the nature of the managed heap and unsafe code, these limitations can easily be overcome with a little ingenuity.