Skip to content

Instantly share code, notes, and snippets.

@qdk0901
Last active September 14, 2018 09:39
Show Gist options
  • Save qdk0901/b467345cc6047d45a346ab8df5f4d3b0 to your computer and use it in GitHub Desktop.
Save qdk0901/b467345cc6047d45a346ab8df5f4d3b0 to your computer and use it in GitHub Desktop.
pthread wrapper
#ifndef _THREAD_H_
#define _THREAD_H_
#include <pthread.h>
#include <string>
template<typename Tobject>
class CallProxy
{
typedef void (Tobject::*Function)();
public:
void Set(Tobject* obj, Function f);
void Call();
private:
Function mFunction;
Tobject* mObj;
};
template<typename Tobject>
class Thread
{
typedef void (Tobject::*Function)();
public:
static Thread<Tobject>* CreateThread(const char* name, Tobject* obj, Function f);
void StopThread();
private:
Thread(const char* name, Tobject* obj, Function f);
void RunLoop();
pthread_t* GetThreadId();
static void* thread(void* arg);
private:
CallProxy<Tobject> mProxy;
bool mRunning;
pthread_t mThreadId;
std::string mName;
public:
};
template<typename Tobject>
void CallProxy<Tobject>::Set(Tobject* obj, Function f)
{
mObj = obj;
mFunction = f;
};
template<typename Tobject>
void CallProxy<Tobject>::Call()
{
(mObj->*mFunction)();
}
template<typename Tobject>
void* Thread<Tobject>::thread(void* arg)
{
Thread<Tobject>* t = (Thread<Tobject>*)arg;
t->RunLoop();
return NULL;
}
template<typename Tobject>
void Thread<Tobject>::RunLoop()
{
mRunning = true;
while(mRunning) {
mProxy.Call();
}
printf("Thread[%s] Exit\n", mName.c_str());
}
template<typename Tobject>
pthread_t* Thread<Tobject>::GetThreadId()
{
return &mThreadId;
}
template<typename Tobject>
Thread<Tobject>* Thread<Tobject>::CreateThread(const char* name, Tobject* obj, Function f)
{
Thread<Tobject>* t = new Thread<Tobject>(name, obj, f);
pthread_create(t->GetThreadId(), NULL, thread, t);
return t;
}
template<typename Tobject>
Thread<Tobject>::Thread(const char* name, Tobject* obj, Function f)
{
mName = name;
mProxy.Set(obj, f);
}
template<typename Tobject>
void Thread<Tobject>::StopThread()
{
void* res;
mRunning = false;
pthread_join(mThreadId, &res);
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment