静态成员函数与pthread_create,纯虚函数匹配使用实例

最近在浏览朋友写的代码,发现有一个细节非常值得学习,在这里将代码贴出来简单分享一下:

#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的派生类WorkThread中,arg传入的是WorkThread,此时需要进行指针类型转换,
//将派生类对象的指针转换为基类的指针,此时基类指针指向的是派生类对象中的基类部分 Thread *p_thread = static_cast<Thread*>(arg); //这里利用了动态绑定 p_thread->run(); return NULL; } pthread_t Thread::get_tid() const { return _tid; }
原文地址:https://www.cnblogs.com/zlcxbb/p/6580793.html