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

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


thread.h

/* *
 * @file thread.h
 * @version
 * @date 2011/5/12
 * @author [email protected]
 * @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方法就可以了。其实也完全可以不封装,但可能使得程序的可读性不是那么强把。

你可能感兴趣的:(linux c++ 线程的封装(类java风格))