文件传输项目模块1-线程池

#ifndef THREADPOOL_H
#define THREADPOOL_H

#include<list>
#include"locker.h"//线程的互斥和同步机制


template<typename T>class threadpool
{
public:
	//默认创建8个线程,请求队列最大为10000
	threadpool(int thread_number = 8, int max_requests = 10000);
	~threadpool();
	//往请求队列中添加任务
	bool append(T *request);

private:
	//线程的工作函数,它不断从工作队列中取出任务并执行
	//我们知道类的成员函数在经过编译器处理之后,会变成带有this指针参数的全局函数
	//所以类型注定是不会匹配的。所以必须处理为静态函数,砍掉this指针...
	static void *worker(void *arg);
	void run();
private:
	int m_thread_number;//线程池中的线程数
	int m_max_requests;//请求队列所能允许的最大请求数
	pthread_t m_threads;//描述线程池的数组 大小和线程数相同
	list<T *> m_workqueue;//请求工作队列(先来先服务)
	locker m_queuelocker;//保护请求队列的互斥锁
	sem m_queuestat;//信号量 判断是否有任务需要处理
	bool m_stop;//线程池是否被释放了
};

template<typename T> 
threadpool<T>::threadpool(int thread_number, int max_requests):
m_thread_number(thread_number), m_max_requests(max_requests), m_stop(false), m_threads(NULL)
{
	if((thread_number <= 0) || (max_requests<=0))
	{
		throw std::exception();
	}

	//创建数组用来存放线程号
	m_threads = new pthread_t[m_thread_number];
	if(!m_threads)
	{
		throw std::exception();
	}

	//创建thread_number个线程,并将它们设置为脱离线程
	for(int i=0; i<thread_number; ++i)
	{
		cout<<"create "<<i+1<<" th thread"<<endl;
		if(pthread_create(m_thread[i], NULL, worker, this) != 0)//将this指针传入 可以方便的调用this->worker(); 提高了效率
		{
			delete []m_threads;
			throw std::exception();
		}

		//设置线程状态为非阻塞,结束后立即返回 类似于waitpid
		if( pthread_detack(m_threads[i]) )
		{
			delete [] m_threads;
			throw std::exception();
		}
	}
}

template<typename T> threadpool<T>::~threadpool()
{
	delete [] m_threads;
	m_stop = true;
}

template<typename 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();//v操作 即将信号量加1 以告诉线程有几个请求可以进行处理
	return true;
}

template<typename T> void * threadpool<T>::worker(void *arg)
{
	threadpool *pool = (threadpool *)arg;//获取this指针
	pool->run();//调用run处理
	return pool;
}

template<typename T> void threadpool<T>::run()
{
	while(!m_stop)//
	{
		m_queuestat.wait();//p操作 即将信号量-1 表示已经处理了一个请求
		m_queuelocker.lock();//进行加锁 队请求队列进行操作(删除队头请求)
		if(m_workqueue.empty())//如果请求工作队列为空 解锁 进行下一次循环 继续轮询
		{
			m_queuelocker.unlock();
			continue;
		}
		T *request = m_workqueue.front();//获取将要处理的请求
		m_workqueue.push_front();//该请求出队
		m_queuelocker.unlock();//队列操作完毕 解锁
		if(!request)//请求为空 进行下一次循环 继续进行轮询
		{
			continue;
		}
		request->process();//真正的请求处理函数!!!
	}
}

#endif

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值