线程池实现。
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了线程池实现。相关的知识,希望对你有一定的参考价值。
线程池实现代码:
#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(); } }
本文出自 “剩蛋君” 博客,转载请与作者联系!
以上是关于线程池实现。的主要内容,如果未能解决你的问题,请参考以下文章