Created
February 4, 2013 19:59
-
-
Save travitch/4709193 to your computer and use it in GitHub Desktop.
A pthread_create wrapper to launch any callable object in another thread.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <pthread.h> | |
struct ThreadBase | |
{ | |
virtual ~ThreadBase(){} | |
virtual void* operator() () = 0; | |
}; | |
template<typename CallableObject> | |
struct ThreadTask : public ThreadBase | |
{ | |
CallableObject callable; | |
ThreadTask(const CallableObject & c):callable(c){} | |
virtual ~ThreadTask(){} | |
virtual void* operator() () | |
{ | |
return callable(); | |
} | |
}; | |
void* threadStarter(void* data) | |
{ | |
ThreadBase * helper = reinterpret_cast<ThreadBase*>(data); | |
return (*helper)(); | |
} | |
template<typename CallableObject> | |
int better_pthread_create(CallableObject o, pthread_t &threadObj) | |
{ | |
ThreadBase * th = new ThreadTask<CallableObject>(o); | |
return pthread_create(&threadObj, NULL, threadStarter, | |
reinterpret_cast<void*>(th)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment