线程池实现。
来源:互联网 发布:php安装环境 编辑:程序博客网 时间:2024/05/16 01:16
线程池实现代码:
#pragma once#include<list>#include<cstdio>#include<exception>#include<pthread.h>#include"locker.h"template<class T>class threadpool{public:threadpool(int thread_number = 8,int max_request = 10000);~threadpool();bool append(T* request);private:static void* worker(void *arg);void run();private:int m_thread_number;int m_max_requests;pthread_t* m_threads;std::list<T*> m_workqueue;locker m_queuelocker;sem m_queuestat;bool m_stop;}'template<class T>threadpool<T>::threadpool(int thread_number,int max_request):m_thread_number(thread_number),m_max_requests(max_requests),m_stop(false),m_thread(NULL){if((thread_number > 0)||(max_request<=0)){throw std::exception();}m_threads = new pthread_t(m_thread_number);if(!m_threads){throw std::except();}for(int i = 0;i<thread_number;++i){printf("create the %d thread\n");if(pthread_create(m_thread+i,NULL,worker,this)!= 0){delete[] m_thread;throw std::exception();}if(pthread_detach(m_threads[i])){delete[] m_thread;throw std::exception();}}}template<class T>threadpool<T>::~threadpool(){delete []m_threads;m_stop = true;}template<class T>bool threadpool<T>::append(T* request){m_queuelocker.lock();if(m_workqueue.size() > m_max_requests){m_queuelocker.unlock();return false;}m_workqueue.push_back(request);m_queuelocker.unlock();m_queuestat.post();return true;}template<class T>void* threadpool<T>worker(void *arg){threadpool* pool = (threadpool*)arg;pool->run();return pool;}template<class T>vpoid threadpool<T>::run(){while(!m_stop){m_queuestat.wait();m_queuelocker.lock();if(m_workqueue.empty()){m_queuelocker.unlock();continue;}T* request = m_workqueue.front();m_workqueue.popfront();m_queuelocker.unlock();if(!request){continue;}request->process();}}
本文出自 “剩蛋君” 博客,转载请与作者联系!
0 0
- VC实现线程池
- VC实现线程池
- 线程池及其实现
- 线程池的实现
- VC实现线程池
- 简单线程池实现
- VC实现线程池
- VC实现线程池
- VC实现线程池
- linux 线程池实现
- VC实现线程池
- c++实现线程池
- c实现线程池
- 线程池的实现
- VC实现线程池
- VC实现线程池
- 线程池实现
- 线程池的实现
- SYN攻击
- 动态规划:从新手到专家
- Linux 上实现双向进程间通信管道
- Linux:进程池实现
- Runtime中Swizz_method方法替换
- 线程池实现。
- 1020. Tree Traversals (25)
- HDU 4784-Dinner Coming Soon-BFS
- 单链表的输入和输出(c语言编写)
- Android Design Support Library(一)用TabLayout实现类似网易选项卡动态滑动效果
- Java并发编程:volatile关键字解析
- HTML5 的message的使用
- 小回顾-比较完善的学生简易管理系统
- C++ this指针和构造函数(-)