I was looking for a simple thread library implementation in C++, something like Java's Thread class. I could not find anything ready and easy to use. I have come up with a simple implementation of a Thread class in C++. Please note that I do not claim to have implemented threads, i have just modelled an abstraction called Thread, which can be sub classed by your classes.
POSIX pthreads are used for threading. This library is just a wrapper around it.
I was actually trying to build a ThreadPool library using C++. So, I had to model a Thread Class so that the Thread Pool implementation will be easier (i thought) to conceptualise.
So this is how the Thread class looks like.
#ifndef __VTHREAD_H__
#define __VTHREAD_H__
#include
/* Abstract base class for Thread */
class Thread
{
public:
Thread();
int start();
virtual void execute()=0;
private:
static void *threadExecFunc(void *pData);
pthread_t mThreadId;
};
#endifAs it appears from the code, this is an abstract class which is sub-classed by other classes which want to run as a thread. All sub-classes will implement void execute() , to get their work done in a thread. Following is the implementation of the Thread class:
#include
#include
#include
using namespace std;
Thread::Thread()
{
}
int Thread::start()
{
int ret = pthread_create(&mThreadId, NULL, threadExecFunc, this);
return ret;
}
void *Thread::threadExecFunc(void *pData)
{
Thread *lThread = (Thread *) pData;
lThread->execute();
return NULL;
}
As you can see, all you have to do is sub-class Thread class and implement the execute() function in the class. Following is an example of how to implement the Thread class in your programs.
class MyThread: public Thread{ public: MyThread(/* Get some data to work on */) {} void execute() { while( bHasWorkToDo == true ) { doSomeWork(); }
}
}
int main(){ Thread *lMyThread = new MyThread(/* Pass some data to work on */); lMyThread->start(); }
First, I create an instance of MyThread and then i call start() on the object. This results in MyThread::execute() being executed. Note that all the calls to the pthread library have been encapsulated within the Thread class.
There are many features missing though , for example there is no way to join, destroy , yield etc. I have not even thought about how to implement those methods on this Thread class.
Please take a look at the Java's Thread class here to get an idea of what else can be added to this class here - http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Thread.html
No comments:
Post a Comment