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

转自:http://www.cnblogs.com/zlcxbb/p/6580793.html

#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实际上是线程对象的指针,类型为实际线程的类型<br>     
    //若在Thread的派生类WorkThread中,arg传入的是WorkThread,此时需要进行指针类型转换,<br>  
    //将派生类对象的指针转换为基类的指针,此时基类指针指向的是派生类对象中的基类部分
    Thread *p_thread = static_cast<Thread*>(arg);
    //这里利用了动态绑定
    p_thread->run();
    return NULL;
}

pthread_t Thread::get_tid() const {
    return _tid;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值