////// @file Thread.h/// @brief 线程的封装 , 子类继承并实现自己的功能/// @author guozhiming/// @date 2007-05-16///#ifndef __G_THREAD__#define __G_THREAD__#include "def.h"class G_Thread{ public: /// @brief 构造函数 G_Thread(); /// @brief 析构函数 ~G_Thread(); /// @brief 获得线程id /// /// @return 线程id pthread_t getThreadId(); /// @brief 启动线程 bool Start(); /// @brief 线程停止 void pause(); /// @brief 线程继续运行 void continues(); //看样子这个是与pause相对应的 private: /// @brief 屏蔽SIGUSR1信号 , POSIX标准建议在调用sigwait()等待信号以前,进程中所有线程都应屏蔽该信号,以保证仅有sigwait()的调用者获得该信号 , 如果不屏蔽该信号,在sigwait()之前调用pthread_kill()就会出现User defined signal 1. void maskSIGUSR1(); /// @brief 线程pid pthread_t g_pid; /// @brief 信号 sigset_t g_waitSig; /// @brief 线程运行主函数 /// /// @param arg /// /// @return static void *threadFun(void *arg); protected: virtual void Run() = 0;};#endif
#include "Thread.h"#include "Log.h"G_Thread::G_Thread(){ maskSIGUSR1();//看来这个是通用的。无论怎么用thread,都要加这一句了 // 定义SIGUSR1信号阻塞 sigemptyset(&g_waitSig); sigaddset(&g_waitSig, SIGUSR1);//上面已经用了mask函数,为什么这里还要来一下???}G_Thread::~G_Thread(){}void G_Thread::maskSIGUSR1(){ sigset_t sig; sigemptyset(&sig); sigaddset(&sig , SIGUSR1); pthread_sigmask(SIG_BLOCK , &sig , NULL);}pthread_t G_Thread::getThreadId(){ return g_pid;}void *G_Thread::threadFun(void *arg){ G_Thread *pThread = (G_Thread*)arg; pThread->Run();}bool G_Thread::Start(){ int nRet = pthread_create(&g_pid , NULL , threadFun , this); if(0 == nRet) { nRet = pthread_detach(g_pid); if(nRet == 0) { return true; } } else { return false; } return true;}void G_Thread::pause(){ int sig; sigwait(&g_waitSig , &sig);//又是信号的知识,未了解}void G_Thread::continues(){ pthread_kill(g_pid , SIGUSR1);//信号与线程的交互啊。}
未完全理解透彻。。待整体把握后,再来看看