调用关系:RuntineThreadFunc->LoopRutine->用户CallbackFunc
#ifndef _LOOPTHREAD_H_ #define _LOOPTHREAD_H_ #include <pthread.h> #include <stdint.h> /*Readme: * 该类生成一个新线程,且新线程例程循环执行, * 回调函数由用户实现,通过SetRutine注册 * 调用关系:RuntineThreadFunc->LoopRutine->用户CallbackFunc */ #define DEFINE_THREAD(_thread) pthread_t _thread #define BEGIN_THREAD(_thread, _pfn, _pArg) pthread_create(&_thread, NULL, _pfn, _pArg) #define END_THREAD() pthread_detach(pthread_self()) #define FAILED_THREAD(_t) (_t) != 0 #define SUCCEED_THREAD(_t) (_t) == 0 /*用户最终实现回调函数形式,可以根据函数形式声明不同函数指针,通过LoopRutine适配*/ typedef void (*CallbackFunc)(void* param); class CLoopThread { public: CLoopThread(uint32_t loopinterval_us) :m_loopintervalus(loopinterval_us) { m_bStop = false; m_bStoped = true; m_bStarted = false; //m_pvParam = this;/*not thread safe*/ } ~CLoopThread() { Stop(); } void SetRutine(CallbackFunc pf,void* param) { m_pCallbackFunc = pf; m_pvParam = param; }
void Stop() { m_bStop = true; while(!m_bStoped) { usleep(100000);//LoopRutine还在运行,等它这次完成,sleep100ms } m_bStoped = true;//no need m_bStarted = false; } bool Start() { if(m_bStarted && !m_bStoped) return true; DEFINE_THREAD(t); if(FAILED_THREAD(BEGIN_THREAD(t,RuntineThreadFunc,this) ) ) { perror("BEGIN_THREAD failed"); return false; } while(!m_bStarted)//新线程还没启动,sleep100ms usleep(100000); return true; } void* CLoopThread::RuntineThreadFunc(void* p) { ( (CLoopThread*)p)->LoopRutine(); return NULL; } void CLoopThread::LoopRutine() { m_bStarted = true; m_bStoped = false; while(!m_bStop)//main loop,attention { m_pCallbackFunc(m_pvParam); usleep(m_loopintervalus); } m_bStoped = true; m_bStarted = false; END_THREAD(); } private: CallbackFunc m_pCallbackFunc; void* m_pvParam;//callback参数 /*pthread 标准接口函数*/ static void* RuntineThreadFunc(void* p); /*新线程循环函数,同时调用CallbackFunc作为适配*/ void LoopRutine(); uint32_t m_loopintervalus;//新线程例程间隔时间 bool m_bStop; //是否停止线程 //成对出现 bool m_bStarted; //线程是否已经启动 bool m_bStoped; //线程是否已经停止 }; #endif //_LOOPTHREAD_H_
补充:一个通用生成非循环新线程,具有独立运行能力的类。线程创建的工作在类的内部完成,使得类具有对立运行的性质,熟悉java的同学对下面的实现一定非常熟悉:
#include <stdio.h> #include <pthread.h> #include <string> class ThreadBase { public: virtual ~ThreadBase() {} void SetMessage(const char* message) { message_ = message; } void Start() { pthread_create(&thread_id_, NULL, Hook, this); } void* Join() { void* ret = NULL; pthread_join(thread_id_, &ret); return ret; } virtual void Run() { printf("%s\n", message_.c_str()); } private: static void* Hook(void* object) { ThreadBase* thread_base= static_cast<ThreadBase*>(object); thread_base->Run(); } pthread_t thread_id_; std::string message_; }; class ThreadDerived : public ThreadBase { public: virtual void Run() { printf("a new derived multi-thread object is running\n"); } }; int main(int argc, char** argv) { pthread_t thread_id; char message[] = "hello world"; ThreadBase thread_base; thread_base.SetMessage(message); thread_base.Start(); thread_base.Join(); ThreadDerived thread_derived; thread_derived.Start(); thread_derived.Join(); }