Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

A Thread Pool compatible with Win32 and pthreads API

0.00/5 (No votes)
9 Apr 2008 2  
A cross-platform thread pooling implementation

Introduction

I had a requirement to create a server that could run on Windows and Linux platforms. One of the basic requirements of the server was an efficient thread-pooling scheme. I came across the pthreads API. I already had a thread pooling scheme that used IO Completion ports. Using a few defines and pre-processor directives, I changed the existing thread pool to support the pthread library. I have NOT compiled this on Linux yet.

Requirements:

It uses the STL containers vector and deque.

It also uses the for_each STL algorithm.
The classes themselves do not use MFC, but the demo app is created using MFC Single Document App-Wizard.
Requires pthreads library on non-Win32 platforms.

To Use

To use the native Win32 API, comment the line:

#include <pthread/pthread.h&>

in the header file 'defines.h'.

Step 1: Include the header file thread.h.

Step 2: Derive a class CMyJob from ThreadJob and implement the 'execute' virtual function. After the job to be done in the thread is complete, do not forget to call the 'execute' function of the base class.

Step 3: In the application's initialization, call

CThread::get_threadpool().start(num);

This creates the threads and waits on them.

Step 4: When you have a job to be queued on the pool,

CMyJob* pjob = new CMyJob
// initialize pjob

CThread::get_threadpool().add_job(pjob);

The thread pool executes the job and after the job is completed, CMyJob deletes itself.

Step 5: When the application quits, call

CThread::get_threadpool().stop();

This prevents any more jobs being queued, deletes pending jobs, stops the threads and then returns.

You can obtain the pthreads library from ftp://sources.redhat.com/pub/pthreads-win32/dll-latest to test with pthreads.

In my tests, pthreads on Win32 was a fraction slower than the Win32. This could be because pthreads on Win32 is a wrapper over the native Win32 threads API.

Please send any suggestions to improve this class.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here