采用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=