Skip to content

Instantly share code, notes, and snippets.

@travitch
Created February 4, 2013 19:59
Show Gist options
  • Save travitch/4709193 to your computer and use it in GitHub Desktop.
Save travitch/4709193 to your computer and use it in GitHub Desktop.
A pthread_create wrapper to launch any callable object in another thread.
#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