Thread系列的RAII封装

采用c++封装了Thread,线程私有数据TSD,线程池:

#include<iostream>
#include<pthread.h>
#include<unistd.h>
#include<boost/shared_ptr.hpp>
#include<boost/weak_ptr.hpp>
#include<boost/noncopyable.hpp>
#include<boost/function.hpp>
#include<boost/bind.hpp>
#include<boost/ptr_container/ptr_vector.hpp>
#include<string>
#include<deque>
#include<algorithm>
#include<sys/syscall.h>
#include<stdio.h>
#include<assert.h>
#include"Mutex.hpp"
using namespace std;
using namespace boost;
/*
 *线程类Thread
 */
__thread pid_t t_cacheTid=0;//线程私有数据线程ID避免通过系统调用获得ID
class Thread:noncopyable{
    public:
        typedef function<void()> ThreadFunc;//线程需要执行工作函数
        explicit Thread(const ThreadFunc& a,const string& name=string()):started_(false),
            joinded_(false),pthreadID_(0),tid_(new pid_t(0)),func_(a),name_(name){
            }
        ~Thread(){
            if(started_&&!joinded_){
                pthread_detach(pthreadID_);//分离线程
            }
        }
        void start();
        /*
        {
            assert(!started_);
            started_=true;
            if(pthread_create(&pthreadID_,NULL,&startThread,NULL)){
                started_=false;
                abort();//终止进程刷新缓冲区
            }
        }
        *///###1###使用此处会出错详见http://cboard.cprogramming.com/cplusplus-programming/113981-passing-class-member-function-pthread_create.html
        void join(){//等待线程执行完工作函数
            assert(started_);
            assert(!joinded_);
            joinded_=true;
            pthread_join(pthreadID_,NULL);
        }
        pid_t tid() const{
            if(t_cacheTid=
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值