这两天写了一个关于C++的线程库,刚开始老是出现信号丢失的问题,百思不得其解。后来才发现原来要pthrea_cond_wait和pthread_cond_signal之间要用一个条件变量来控制。例如:while(count==0)pthread_cond_wait();count--;
在pthread_cond_signal处,要用if(count==0)pthread_cond_signal();count++.
下面是我写的线程池代码:
.h文件:
#ifndef __THREAD_POOL_FOR_INOTIFY__
#define __THREAD_POOL_FOR_INOTIFY__
#include
#include
#include
using namespace std;
typedef void* (*TASKFUN)(void* arg);
class Task{
public:
void SetData(void* data){
m_data=data;
}
void SetFun(TASKFUN myFun){
m_fun=myFun;
}
void run();
private:
void* m_data;
TASKFUN m_fun;
};
class ThreadItem;
class ThreadPool{
public:
ThreadPool(int ThreadNum);
int InitPool();
~ThreadPool();
int AddTask(Task* task);
protected:
friend class ThreadItem;
private:
int iMaxThread;
static pthread_mutex_t mutex;
pthread_mutexattr_t mutexattr;
pthread_condattr_t condattr;
static pthread_cond_t cond;
static int busyNums;
vector
static queue
};
class ThreadItem{
public:
ThreadItem(){
busy=false;
stop=false;
pthread_create(&th_t, NULL,ThreadWork, NULL);
}
bool inline IsBusy(){return busy==true;}
void inline SetBusy(){busy = true;}
void inline SetIdle(){busy = false;};
void inline SetStop(){stop=true;}
static void* ThreadWork(void* Para);
pthread_t th_t;
~ThreadItem()
{
if(!stop)stop=true;
pthread_cond_signal(&(ThreadPool::cond));
cout<<"th_t:"< pthread_join(th_t, NULL); } private: static bool busy; static bool stop; }; #endif