linux c++ 线程的封装(类java风格)

linux下线程采用pthread.h,采用的是c语言的风格,为了更加面向对象话,我在写程序的时候给封装成了一个类,用到了一些内部的库,但是去掉内部的库,也无伤大雅。懒得去改程序了,所以没有去处某些内部的头文件和函数的调用。


thread.h

/* *
 * @file thread.h
 * @version
 * @date 2011/5/12
 * @author wangyou@baidu.com
 * @brief 对线程进行了简单的封装(java风格)
*
*/
#pragma once

#include 

#include   //  线程

class thread {
public:
     /* *
     * @brief   构造函数
     * @param   无
     * @return  无
    *
*/
    thread() : _id( 0) {
    }

     /* *
     * @brief   启动线程
     * @param   无
     * @return  无
    *
*/
     void start();
     /* *
     * @brief   线程睡眠
     * @param   睡眠时间(ms)
     * @return  无
    *
*/
     static  void sleep(uint32_t msec);  //  睡眠msec毫秒
     /* *
     * @brief   获取线程id
     * @param   无
     * @return  线程id
    *
*/
    pthread_t get_thread_id();
     /* *
     * @brief   等待线程退出
     * @param   无
     * @return  无
    *
*/
     void wait_for_exit();  //  等待线程退
protected:
     virtual  void _run() =  0//  线程工作函数
private:
    pthread_t _id;  //  线程id
     static  void *thread_func( void *args);
};

thread.h

#include 
#include 
#include  " thread.h "

void thread::start() {
     int rc = ul_pthread_create(&_id, NULL, thread_func,  this);
     if (rc !=  0) {
        ul_writelog(UL_LOG_FATAL,  " 创建线程失败 ");
        exit( 1);
    }
}


pthread_t thread::get_thread_id() {
     return _id;
}

void thread::sleep(uint32_t msec) {
     struct timespec st;
    st.tv_sec = msec /  1000;
    st.tv_nsec = (msec %  1000) *  1000 *  1000;
     if (nanosleep(&st, NULL) == - 1) {
        ul_writelog(UL_LOG_WARNING,  " 休眠失败 ");
    }
}

void *thread::thread_func( void *args) {
    thread *t = (thread*)args;
    t -> _run();
     return NULL;
}

void thread::wait_for_exit() {
     if (_id !=  0) {
         if(ul_pthread_join(_id, NULL) !=  0) {
            ul_writelog(UL_LOG_FATAL,  " 等待线程结束失败 ");
        }  else {
            _id =  0;
        }
    }
}

注意里面用的ul_pthread_create,直接改成pthread_create就可以,日志的打印程序就不要了。用的时候很简单,直接继承字thread类,然后实现run虚方法,用的时候,只要调用start方法就可以了。其实也完全可以不封装,但可能使得程序的可读性不是那么强把。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值