参考自 pthreadcc 库的 ThreadBase 类
用法:继承该类,重写 execute 方法,调用父类的 launchThread 方法启动线程
Thread.h
// // Thread.h // MinaCppClient // // Created by yang3wei on 7/23/13. // Copyright (c) 2013 yang3wei. All rights reserved. // #ifndef __MinaCppClient__Thread__ #define __MinaCppClient__Thread__ #include <netdb.h> class Thread { public: Thread(); ~Thread(); void launchThread(); protected: virtual void* initialise(); virtual void* execute(); virtual void cleanUp(); private: pthread_t m_oThread; static void* threadMain(void* in_pArg); }; #endif /* defined(__MinaCppClient__Thread__) */Thread.cpp
// // Thread.cpp // MinaCppClient // // Created by yang3wei on 7/23/13. // Copyright (c) 2013 yang3wei. All rights reserved. // #include "Thread.h" #include <pthread.h> #include <stdio.h> Thread::Thread() { // printf("Thread::Thread() "); } Thread::~Thread() { // printf("Thread::~Thread() "); } void* Thread::initialise() { // printf("Thread::initialise() "); return NULL; } void* Thread::execute() { // printf("Thread::execute() "); return NULL; } void Thread::cleanUp() { // printf("Thread::cleanUp() "); } void Thread::launchThread() { // printf("Thread::launchThread() "); do { pthread_attr_t tmp_oThreadAttr; if (pthread_attr_init(&tmp_oThreadAttr) != 0) { printf("launchThread()->pthread_attr_init() error! "); break; } if (pthread_attr_setdetachstate(&tmp_oThreadAttr, PTHREAD_CREATE_DETACHED) != 0) { printf("launchThread()->pthread_attr_setdetachstate() error! "); pthread_attr_destroy(&tmp_oThreadAttr); break; } if (pthread_create(&m_oThread, &tmp_oThreadAttr, &(Thread::threadMain), this) != 0) { printf("launchThread()->pthread_create() error! "); break; } printf("Launch receive thread successfully! "); } while (0); } void* Thread::threadMain(void* in_pThread) { // printf("Thread::threadMain() "); Thread* t_pThread = (Thread*)in_pThread; void* t_pRetVal; if ((t_pRetVal = t_pThread->initialise()) == NULL) { t_pRetVal = t_pThread->execute(); } t_pThread->cleanUp(); return t_pRetVal; }