threadpool 简单线程池实现样例

简单易用的线程池

  • 缘由

因为经常遇到一些不多不少的计算情况,单线程跑嫌慢多线程优化又因为问题过于简单不想写代码,所以
不知道在那上找到了这么一个简单易用的线程池…若知道出处希望评论一下。

  • 阅读

因为需求的简单,所以这个简化的线程池刚好适用.主体代码也就三部分:构造线程空间,接收任务,释放线程空间.

  1. 构造了给定数量的空线程,并阻塞住,等待放入任务的信号,有任务进来则执行,之后继续阻塞等待直至线程池析构。
  2. 放入任务时,绑定参数打包以便后续的调用然后放入队列,同时通知某个线程进行工作
  3. 线程池被析构时,通知所有线程继续完成未完成的工作,之后释放所有线程
  • 参考

https://zh.cppreference.com/w/cpp

class ThreadPool
{
public:
	ThreadPool(size_t);
	template<class F,class... Args)
	auto enqueue(F &&f,Args &&... args)
	->std::future<typename std::result_of<F(Args...)>::type>;
	~ThreadPool();
private:
	std::vector<std::thread> workers;
	std::queue<std::function<void()>> tasks;

	std::mutex queue_mutex;
	std::condition_variable condition;
	bool stop;
}


inline ThreadPool::ThreadPool(size_t threads):stop(false)
{
	for(size_t i=0;i<threads;++i)
	{
		workers.emplace_back([this]{
			while(true)
			{
				std::function<void()> task;
				{	
					std::unique_lock<std::mutex> lock(this->queue_mutex);
					this->condition.wait(lock,[this]{
						return this->stop&&!this->tasks.empty();
					});
					if(this->stop&&this.tasks.empty())
					{
						return;
					}
					task = std::move(this->tasks.front());
					this->tasks.pop();
				}
				task();
			}
		});
	}
}


template<class F,class ...Args>
auto ThreadPool::enqueue(F &&f,Args &&... args)
->std::future<typename std::result_of<F(Args...)>::type>
{
	using result_type = typename std::result_of<F(Args...)>::type;
	auto task = std::make_shared<std::package_task<result_type>>(
		std::bind(std::forward<F>(f),std::forward<Args>(args)...);
	);
	std::future<result_type> res = task->get_future();
	{
		std::unique_lock<std::mutex> lock(queue_mutex);
		if(stop)
		{
			throw std::runtime_error("enqueue is not allowed on stopped pool ");
		}
		tasks.emplace([task](){(*task)();});
	}
	condition.notify_one();
	return res;
}

inline ThreadPool::~ThreadPool()
{
	{
		std::unique_lock<std::mutex> lock(queue_mutex);
		stop = true;
	}
	condition.notify_all();
	for(std::thread &worker : workers)
	{
		worker.join();
	}
}
  • 调用

对stl有了解就行

int main()
{
	typedef int ResultType;
	ThreadPool pool(3);
	std::vector<std::future<ResultType>> res;
	res.emplace_back(pool.enqueue([](){return 1;}));
	res.emplace_back(pool.enqueue([](){return 2;}));
	res.emplace_back(pool.enqueue([](){return 3;}));
	for(auto && re : res)
	{std::cout<< re.get()<<std::endl;}
}
delphi线程池单元文件uThreadPool.pas,用法如下 type TRecvCommDataWorkItem=class(TWorkItem) public // updatetime,addtime:TDateTime; // orderid,ordertype,urljson,loadcount,savepath:string; url,Filename:string; total,order:Integer; _orderid:string; failedcount:Integer; IFCoverFile:Boolean; // 线程处理请求时触发的事件 procedure DealwithCommRecvData(Sender: TThreadsPool; WorkItem: TWorkItem; aThread: TProcessorThread); // 线程初始化时触发的事件 procedure TProcessorThreadInitializing(Sender: TThreadsPool; aThread:TProcessorThread); // 线程结束时触发的事件 procedure TProcessorThreadFinalizing(Sender: TThreadsPool; aThread:TProcessorThread); //任务队列空时触发的事件 procedure TQueueEmpty(Sender: TThreadsPool; EmptyKind: TEmptyKind); end; 先声明一个类 然后用法 FThreadPool := TThreadsPool.Create(nil); // 创建线程池 FThreadPool.ThreadsMin := 10; // 初始工作线程数 FThreadPool.ThreadsMax := 100; // 最大允许工作线程数 AWorkItem := TRecvCommDataWorkItem.Create; ISAllOverLoad:=False; AWorkItem.url:=urljson; AWorkItem.order:=i; AWorkItem.total:=JA.Count; AWorkItem.Filename:=savefilepath; AWorkItem._orderid:=orderid; AWorkItem.IFCoverFile:=IFCoverFile; FThreadPool.AddRequest(AWorkItem,True); // 向线程池分配一个任务 FThreadPool.OnProcessRequest := AWorkItem.DealwithCommRecvData; FThreadPool.OnThreadInitializing := AWorkItem.TProcessorThreadInitializing; FThreadPool.OnThreadFinalizing := AWorkItem.TProcessorThreadFinalizing; FThreadPool.OnQueueEmpty := AWorkItem.TQueueEmpty; 仔细看下线程池单元的函数说明轻松搞定。 procedure TRecvCommDataWorkItem.TQueueEmpty(Sender: TThreadsPool; EmptyKind: TEmptyKind); begin if EmptyKind=ekProcessingFinished then begin try if Assigned(geturl) then //存在的bug 如果下载文件存在的不行 begin //Sleep(200); //激活线程可能会发生在 休眠之前!! ISAl
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值