线程池实现。

线程池实现代码:

#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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值