Friday, July 16, 2010

A ThreadPool Class

This is a basic implementation of a thread pool written in .NET 2.0 ThreadPool The class AliGInterview.Threading.ThreadPool is a very basic implementation of a thread pool class. This class is responsible for accepting the request from client codes, queue the requests and informing the running threads to pick the newly arrived requests when they are done with their current task Clients have to call the method QueueUserWorkItem to queue their process requests. This method follows the same syntax as its counterpart in System.Threading.ThreadPool of .NET 2.0 and is the only public method of the classSignaling There are two waiting handles that are responsible for orchestrating the queue signaling and termination signaling
  • _itemQueuedEvent will be set when a new item has been queued and requests processing
  • _stopAll will be signaled to terminate all of the threads in the thread pool
Synchronization All the requests are queued using a member called _waitQueue; this queue is accessible to all of the threads including the client thread, to synchronize access to this object _queueAccessSync is used. Locking is imposed at the Enqueue and Dequeue time. Running Threads The Threadpool class spawns different threads to process the queued items, all of these threads are using the thread procedure called ControllerThreadProcedure. This method contains an infinite loop and waits for the parent ThreadPool class to signal its termination by waiting for _stopAll event. This procedure picks one of the queued items when _itemQueuedEvent is signaled and runs its callback in a try-catch block. When it is done with the execution it goes back to the waiting mode by calling WaitHandle.WaitAny(continueSignals); Processing ThreadsThe client code can determine the number of the threads in the thread pool by passing it to the constructor, otherwise the thread pool will be created with 5 running threads. All of the threads are constructed inside the StartWorkingThreads function. Disposal The thread pool class must be disposed to terminate all of its running threads. The Test Application The application comes with one form that contains two groups boxes and one output list control The first group box is for creating the thread pool and the use should determine the number of threads in the thread pool, upon successful creation the creation message will be displayed and the task manager group box will be activated. After the ThreadPool is created successfully the user determines the number of tasks that must be added to the thread pool The output of each task is a custom data that determines the task number (starting with zero) the thread ID that has processed the task.

No comments:

Post a Comment