65.9K
CodeProject is changing. Read more.
Home

A simple thread pool class

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.95/5 (15 votes)

Jan 1, 2004

viewsIcon

87900

downloadIcon

1932

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.