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

A simple thread pool class

0.00/5 (No votes)
31 Dec 2003 1  
A simple thread pool class

Introduction

ThreadPool is a very important concept to improve the performance of multi-threaded programs. Generally the threadpool includes an asynchronous queue to keep the tasks that a thread can pick a task from and the caller can put a task into.

In the threadpool code, we define an Asynchronous queue, a Job interface and a ThreadPool class to manage the threads. The synchronization is the core of the threadpool.

I have implemented some classes that will make it easier for you.

Details

It is very easy to use the threadpool class. First you should implement your job class by inheriting the "Job" interface. That means you need to implement two interface functions.

class Job {
public:
    virtual void Process() = 0;
    virtual ~Job() {};
};

For example, you define your job class as

class MyJob1 : public Job {
public:
    MyJob1(int index) : data(index) {};
    virtual void Process() {
        cout << data << endl;
    }
    ~MyJob1() {};

private:
    int data;
};

The "Process" is called by the thread. Then you can use the threadpool as following.

ThreadPool tp(4, TRUE);
Job *job = new MyJob1(0);
tp.Assignment(job);

Of course I intentionally made it simple for you to understand how to create and use threadpool. You can freely modify it and add other features.

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