最近在浏览朋友写的代码,发现有一个细节非常值得学习,在这里将代码贴出来简单分享一下:
- #ifndef THREAD_H_
- #define THREAD_H_
- #include <pthread.h>
- #include <stdexcept>
- #include "Copyable.h"
- /*
- * 这个线程类是个抽象类,希望派生类去改写它
- */
- class Thread : public Copyable{
- public:
- Thread();
- virtual ~Thread();
- void start();
- void join();
- static void *thread_func(void *);
- /*
- * 这是个纯虚函数
- */
- virtual void run() = 0;
- pthread_t get_tid() const;
- protected:
- pthread_t _tid;
- };
- #endif /* THREAD_H_ */
pthread_create 的定义如下:
新建线程从 void *(*start_routine)(void *) 函数的地址开始运行,该函数直邮一个无类型指针参数 arg。如果需要向 start_routine 函数传递的参数有一个以上,那么需要把这些参数放到一个结构中,然后把这个结构的地址作为 arg 参数传入。
- #include <pthread.h>
- int
- pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg);
下面对 Thread 的实现中,采用静态成员函数(被类的所有对象共享,包括该类的派生类对象)的指针 Thread::thread_func(如果要调用公用的静态成员函数,要用类名:: 静态成员函数名)作为回调函数,this 指针作为参数传入。并且在静态成员函数 Thread::thread_func 中调用 run(虚函数,动态绑定,后续继承 Thread 的类只实现 run 就可以了,特别巧妙)。手法特别巧妙,值得学习。
- #include "Thread.h"
- Thread::Thread() :
- _tid(pthread_self()) {
- }
- Thread::~Thread() {
- }
- void Thread::start() {
- //采用静态函数的指针作为回调函数
- //this作为线程的参数
- pthread_create(&_tid, NULL, Thread::thread_func, this);
- }
- void Thread::join() {
- pthread_join(_tid, NULL);
- }
- void *Thread::thread_func(void *arg) {
- //arg实际上是线程对象的指针,类型为实际线程的类型
- Thread *p_thread = static_cast<Thread*>(arg);
- //这里利用了动态绑定
- p_thread->run();
- return NULL;
- }
- pthread_t Thread::get_tid() const {
- return _tid;
- }
来源: http://www.bubuko.com/infodetail-1988167.html