本文主要是介绍tars源码漫谈第27篇------tc_thread.h/tc_thread.cpp(包含线程锁的重要线程类),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
来看看tc_thread中的线程类, TC_ThreadControl是线程控制类, 对线程句柄进行操作, 常见操作如:
void TC_ThreadControl::join()
{if(pthread_self() == _thread){throw TC_ThreadThreadControl_Exception("[TC_ThreadControl::join] can't be called in the same thread");}void* ignore = 0;int rc = pthread_join(_thread, &ignore);if(rc != 0){throw TC_ThreadThreadControl_Exception("[TC_ThreadControl::join] pthread_join error ", rc);}
}void TC_ThreadControl::detach()
{if(pthread_self() == _thread){throw TC_ThreadThreadControl_Exception("[TC_ThreadControl::join] can't be called in the same thread");}int rc = pthread_detach(_thread);if(rc != 0){throw TC_ThreadThreadControl_Exception("[TC_ThreadControl::join] pthread_join error", rc);}
}
这很简单, 仅仅是封装而已。
如下类是虚基类, easy:
class TC_Runable
{
public:virtual ~TC_Runable(){};virtual void run() = 0;
};
在看看最重要的TC_Thread:
class TC_Thread : public TC_Runable
{
public:/*** @brief 构造函数*/TC_Thread();/*** @brief 析构函数*/virtual ~TC_Thread(){};/*** @brief 线程运行*/TC_ThreadControl start();/*** @brief 获取线程控制类.** @return ThreadControl*/TC_ThreadControl getThreadControl() const;/*** @brief 线程是否存活.** @return bool 存活返回true,否则返回false*/bool isAlive() const;/*** @brief 获取线程id.** @return pthread_t 线程id*/pthread_t id() { return _tid; }protected:/*** @brief 静态函数, 线程入口. * * @param pThread 线程对象*/static void threadEntry(TC_Thread *pThread);/*** @brief 运行*/virtual void run() = 0;protected:/*** 是否在运行*/bool _running;/*** 线程ID*/pthread_t _tid;/*** 线程锁*/TC_ThreadLock _lock;
};}
如下的_lock不就是我们的线程锁吗? 别忘了, 它兼具互斥锁和条件变量的管理能力
/*** 线程锁*/TC_ThreadLock _lock;
cpp中的的如下两个函数在tars框架中, 起到了重要的作用:
void TC_Thread::threadEntry(TC_Thread *pThread)
{pThread->_running = true;{TC_ThreadLock::Lock sync(pThread->_lock);pThread->_lock.notifyAll();}try{pThread->run();}catch(...){pThread->_running = false;throw;}pThread->_running = false;
}TC_ThreadControl TC_Thread::start()
{TC_ThreadLock::Lock sync(_lock);if(_running){throw TC_ThreadThreadControl_Exception("[TC_Thread::start] thread has start");}int ret = pthread_create(&_tid,0,(void *(*)(void *))&threadEntry,(void *)this);if(ret != 0){throw TC_ThreadThreadControl_Exception("[TC_Thread::start] thread start error", ret);}_lock.wait();return TC_ThreadControl(_tid);
}
其实, 意思也不复杂。 在后面介绍tars源码框架中, 我们会继续和上面两个函数打交道, 到时也会进一步叙述。
总之, 搞懂TC_Thread类, 很关键。
这篇关于tars源码漫谈第27篇------tc_thread.h/tc_thread.cpp(包含线程锁的重要线程类)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!