造轮子之线程控制类的封装

线程控制类的封装

线程常用方法
int pthread_join(pthread_t thread, void **retval);
int pthread_detach(pthread_t thread);
pthread_t pthread_self(void);
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                          void *(*start_routine) (void *), void *arg);
定义
/**
 * @brief  线程控制异常类
 */
struct YR_ThreadThreadControl_Exception : public YR_Exception
{
   YR_ThreadThreadControl_Exception(const string &buffer) : YR_Exception(buffer){};
    YR_ThreadThreadControl_Exception(const string &buffer, int err) : YR_Exception(buffer, err){};
    ~YR_ThreadThreadControl_Exception() throw() {};
};

/**
 * @brief  线程控制类
 */
class YR_ThreadControl
{
public:
    /**
     * @brief  构造, 表示当前运行的线程,
     *          join和detach在不能在该对象上调用
    */
    YR_ThreadControl();
    /**
     * @return explicit
     */
    explicit YR_ThreadControl(pthread_t);
    /**
     * @brief  等待当前线程结束, 不能在当前线程上调用
     */
    void join();

    /**
     * @brief  detach, 不能在当前线程上调用
     */
    void detach();
    /**
     * @brief  获取当前线程id.
     *
     * @return pthread_t当前线程id
     */
    pthread_t id() const;
    /**
     * @brief  休息ms时间. 
     *  
     * @param millsecond 休息的时间,具体ms数字
     */
    static void sleep(long millsecond);
    /**
     * @brief  交出当前线程控制权
     */
    static void yield();
private:
    pthread_t _thread;
};
实现
构造和析构
YR_ThreadControl::YR_ThreadControl(pthread_t thread) : _thread(thread)
{
}
YR_ThreadControl::YR_ThreadControl() : _thread(pthread_self())
{
}
控制方法
void YR_ThreadControl::join()
{
    if(pthread_self() == _thread)
    {
        throw YR_ThreadThreadControl_Exception("[YR_ThreadControl::join] can't be called in the same thread");
    }

    void* ignore = 0;
    int rc = pthread_join(_thread, &ignore);
    if(rc != 0)
    {
        throw YR_ThreadThreadControl_Exception("[YR_ThreadControl::join] pthread_join error ", rc);
    }
}

void YR_ThreadControl::detach()
{
    if(pthread_self() == _thread)
    {
        throw YR_ThreadThreadControl_Exception("[YR_ThreadControl::join] can't be called in the same thread");
    }

    int rc = pthread_detach(_thread);
    if(rc != 0)
    {
        throw YR_ThreadThreadControl_Exception("[YR_ThreadControl::join] pthread_join error", rc);
    }
}

pthread_t YR_ThreadControl::id() const
{
    return _thread;
}

void YR_ThreadControl::sleep(long millsecond)
{
    struct timespec ts;
    ts.tv_sec = millsecond / 1000;
    ts.tv_nsec = (millsecond % 1000)*1000000;
    nanosleep(&ts, 0);
}

void YR_ThreadControl::yield()
{
    sched_yield();
}
线程基类的定义
class YR_Runable
{
public:
    virtual ~YR_Runable(){};
    virtual void run() = 0;
};

/**
 * @brief 线程基类. 
 * 线程基类,所有自定义线程继承于该类,同时实现run接口即可, 
 *  
 * 可以通过YR_ThreadContorl管理线程。
 */
class YR_Thread : public YR_Runable
{
public:
    YR_Thread();
    virtual ~YR_Thread(){};

    /**
     * @brief  线程运行
     */
    YR_ThreadControl start();

    /**
     * @brief  获取线程控制类.
     *
     * @return ThreadControl
     */
    YR_ThreadControl getThreadControl() const;

    /**
     * @brief  线程是否存活.
     *
     * @return bool 存活返回true,否则返回false
     */
    bool isAlive() const;

    /**
     * @brief  获取线程id.
     *
     * @return pthread_t 线程id
     */
    pthread_t id() { return _tid; }

protected:

    /**
     * @brief  静态函数, 线程入口. 
     *  
     * @param pThread 线程对象
     */
    static void threadEntry(YR_Thread *pThread);

    /**
     * @brief  运行
     */
    virtual void run() = 0;

protected:
    /**
     * 是否在运行
     */
    bool            _running;

    /**
     * 线程ID
     */
    pthread_t        _tid;

    /**
     * 普通线程锁
     */
    YR_ThreadLock   _lock;
};

实现
构造
YR_Thread::YR_Thread() : _running(false),_tid(-1)
{
}
线程入口
void YR_Thread::threadEntry(YR_Thread *pThread)
{
    pThread->_running = true;
    {
        //YR_ThreadLock::Lock -> 
        //	YR_Monitor<YR_ThreadMutex, YR_ThreadCond>::YR_LockT<YR_Monitor<YR_ThreadMutex, 
        //		YR_ThreadCond>>
        //构造时加锁,析构时解锁
        YR_ThreadLock::Lock sync(pThread->_lock);
        pThread->_lock.notifyAll();
    }

    try
    {
        pThread->run();
    }
    catch(...)
    {
        pThread->_running = false;
        throw;
    }
    pThread->_running = false;
}

线程启动
YR_ThreadControl YR_Thread::start()
{
    //构造时加锁,析构时解锁
    YR_ThreadLock::Lock sync(_lock);

    if(_running)
    {
        throw YR_ThreadThreadControl_Exception("[YR_Thread::start] thread has start");
    }

    int ret = pthread_create(&_tid,
                   0,
                   (void *(*)(void *))&threadEntry,
                   (void *)this);

    if(ret != 0)
    {
        throw YR_ThreadThreadControl_Exception("[YR_Thread::start] thread start error", ret);
    }

    _lock.wait();

    return YR_ThreadControl(_tid);
}
其他函数实现
YR_ThreadControl YR_Thread::getThreadControl() const
{
    return YR_ThreadControl(_tid);
}

bool YR_Thread::isAlive() const
{
    return _running;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值