线程池实现代码:
#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(); } }
时间: 2024-10-27 03:41:04