#include<cstdio>
#include<queue>
#include<pthread.h>
#include<cstdlib>
#include<unistd.h>
#define MAX_QUEUE 10
#define MAX_THREAD 5
typedef void(*handler_t)(int);
class ThreadTask
{
private:
int _data;
handler_t _handler;
public:
ThreadTask(){}
ThreadTask(int data,handler_t handler):_data(data),_handler(handler){}
void Run()
{
_handler(_data);
}
};
class BlockQueue
{
private:
int _capacity;//队列容量
std::queue<ThreadTask> _queue;
pthread_mutex_t _mutex;
pthread_cond_t _cond_pro;
pthread_cond_t _cond_cus;
public:
BlockQueue(int que=MAX_QUEUE):_capacity(que)
{
pthread_mutex_init(&_mutex,NULL);
pthread_cond_init(&_cond_pro,NULL);
pthread_cond_init(&_cond_cus,NULL);
}
~BlockQueue()
{
pthread_mutex_destroy(&_mutex);
pthread_cond_destroy(&_cond_pro);
pthread_cond_destroy(&_cond_cus);
}
bool Push(const ThreadTask& data)
{
pthread_mutex_lock(&_mutex);
while(_queue.size()==_capacity)
{
pthread_cond_wait(&_cond_pro,&_mutex);
}
_queue.push(data);
pthread_cond_signal(&_cond_cus);
pthread_mutex_unlock(&_mutex);
return true;
}
//输出型参数 传地址 输入输出型 * & 不加const
bool Pop(ThreadTask* data)
{
pthread_mutex_lock(&_mutex);
while(_queue.empty())
{
pthread_cond_wait(&_cond_cus,&_mutex);
}
*data=_queue.front();
_queue.pop();
pthread_cond_signal(&_cond_pro);
pthread_mutex_unlock(&_mutex);
return true;
}
};
class ThreadPool
{
private:
int _max_thread;
BlockQueue _queue;
private:
static void* thr_entry(void* arg)//含this指针不符合入口函数格式,需要设置为静态成员函数
{
ThreadPool* p=(ThreadPool*)arg;
while(1)
{
ThreadTask task;
p->_queue.Pop(&task);//获取一个任务节点
task.Run();
}
return NULL;
}
public:
ThreadPool(int maxq=MAX_QUEUE,int maxt=MAX_THREAD):_max_thread(maxt),_queue(maxq)
{
int ret;
pthread_t tid;
for(int i=0;i<MAX_THREAD;++i)
{
ret = pthread_create(&tid,NULL,thr_entry,this);
if(ret!=0)
{
exit(-1);
}
pthread_detach(tid);
}
}
bool _PushTask(const ThreadTask& Task)
{
_queue.Push(Task);
return true;
}
};
void testfunc(int data)
{
printf("%p--get data:%d,sleep %d sec\n",pthread_self(),data,(data%3)+1);
sleep((data%3)+1);
}
int main()
{
ThreadPool pool;
for(int i=0;i<10;++i)
{
ThreadTask task(i,testfunc);
pool._PushTask(task);
}
while(1)sleep(1);
return 0;
}
Linux-线程池的实现(多线程+条件变量任务队列)
最新推荐文章于 2024-08-21 18:16:36 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)