多线程Thread类不同封装实现

  • 多线程Thread类实现
    1.C语言实现方式:通过建立多个全局线程回调函数实现
    2.面向对象实现方式:通过多态特性实现,虚函数在派生类中不同的行为方式
    3.基于对象实现方式:通过boost::function和bind实现
  • - 对于Linux线程创建方式:
int pthread_create(pthread_t *restrict thread,  
        const pthread_attr_t *restrict attr,  
        void *(*start_routine)(void*), void *restrict arg);  

参数1.线程ID
参数2.线程属性
参数3.线程回调函数
参数4.回调函数

  1. C语言实现线程方式:

        通过建立全局线程回调函数实现,对于多个线程多个 不同任务需要建立多个全局函数,例子
    
void threadFunction1(void* arg)
{
    printf("child thread 1\n");
    pthread_exit(NULL);
}
void threadFunction2(void* arg)
{
    printf("child thread 2\n");
    pthread_exit(NULL);
}
int main(){
    pthread_t thread1;
    pthread_t thread2;
    pthread_create(&thread1,NULL,threadFunction1,NULL);
    pthread_create(&thread2,NULL,threadFunction2,NULL);
    pthread_join(thread1,NULL);
    pthread_join(thread2,NULL);
    return 0;
} 
  1. 面向对象封装方式

    虚函数在派生类中不同的行为方式
    
class Thread
{
public:
    Thread(){}
    virtual ~Thread(){}
    void start()
    {
        pthread_create(&_thread,NULL,thread_rountine,this);
    }
    void join()
    {
        pthread_join(_thread,NULL);
    }
private:
static void* thread_rountine(void* arg)
{
    // 不同的线程调用同样的thread_rountine函数,this指针指向不同的线程派生类,执行派生类中的run行为
    Thread* thread = static_cast<Thread*>(arg);
    thread->run();
    return NULL;
}
virtual run()=0;
pthread_t _thread;
};

在prthread_create中为什么不能传递类的成员函数,使用静态的成员函数,因为pthread_create的参数三是一个普通的函数,而类的成员函数隐含传递一个this指针。
3. 基于对象封装方式(muduo库实现方式 boost::function/bind)

    通过boost::function和bind实现
class Thread
{
public:
    typedef boost::function<void ()> ThreadFunc;
    explicit Thread(const ThreadFunc& func):_func(func){}
    ~Thread(){}
    void start(){pthread_create(&_thread,NULL,thread_rountine,this);}
    void join(){pthread_join(_thread,NULL);}
private:
    ThreadFunc _func;
    pthread_t _thread;
    void run()
    {
        _func();
    }
    static void* thread_rountine(void* arg)
    {
        // boost::function类似于一种函数指针的声明,boost::bind类似于绑定一个函数
        // 对于不同线程执行不同的行为时,只需要通过boost::bind改变即可实现。
        Thread* thread = static_cast<Thread*>(arg);
        thread->run();
        return NULL;
}
};
class Foo
{
public:
void MemberFun()
{
    cout<<"child thread1"<<endl;
}
void MemberFun1(int count)
{
    cout<<"child thread2:"<<count<<endl;
}
};
int main()
{
    Foo foo1();
    Foo foo2();
    Thread t(boost::bind(&Foo::MemberFun, &foo));
    Thread t1(boost::bind(&Foo::MemberFun1,&foo2,3));
}
  1. 两种方式比较

    个人观点:
    继承实现的方式耦合性强,当功能扩展时,都需要建立新的派生类实现run方法
    对于基于对象方式来说,耦合性低,对于功能扩展只需要编写一个函数就可以了,扩展性强

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值