互联网络程序设计实验实验.docx

互联网络程序设计实验实验.docx

ID:55178512

大小:12.20 KB

页数:3页

时间:2020-04-30

互联网络程序设计实验实验.docx_第1页
互联网络程序设计实验实验.docx_第2页
互联网络程序设计实验实验.docx_第3页
资源描述:

《互联网络程序设计实验实验.docx》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库

1、线程与线程池封装为了充分利用多核的优势,我们利用多线程来进行任务处理,但线程也同样不能滥用,会带来一下几个问题:1.线程本身存在开销,系统必须为每个线程分配如栈,TLS(线程局部存储),寄存器等。2.线程管理会给系统带来开销,context切换同样会给系统带来成本。3.线程本身是可以重用的资源,不需要每次都进行初始化。所以往往在使用中,我们无需把线程与task任务进行一对一对应,只需要预先初始化有限的线程个数来处理无限的task任务即可,线程池应运而生,原理也就是如此。一下主要基于c++11标准,以及配套的thread,mutex,condition_var

2、iable配套标准库设施实现ThreadPool类的封装。1ThreadPool类的设计ThreadPool主要封装了一个线程队列workers和一个任务队列tasks,以及相应的互斥信号量mutex和条件变量condition。在该类的设计中大量采用了c++11新标准中的设施,如future模块,以及vector中的emplace方法。ThreadPool源代码如下:ThreadPool.h#ifndefTHREAD_POOL_H#defineTHREAD_POOL_H#include#include#include

3、ry>#include#include#include#include#include#includeclassThreadPool{public:ThreadPool(size_t);templateautoenqueue(F&&f,Args&&...args)->std::future::type>;~Thread

4、Pool();private://needtokeeptrackofthreadssowecanjointhemstd::vectorworkers;//thetaskqueuestd::queue>tasks;//synchronizationstd::mutexqueue_mutex;std::condition_variablecondition;boolstop;};//theconstructorjustlaunchessomeamountofworkersinlineThrea

5、dPool::ThreadPool(size_tthreads):stop(false){for(size_ti=0;itask;{std::unique_locklock(this->queue_mutex);this->condition.wait(lock,[this]{returnthis->stop

6、

7、!this->tasks.empty();});if(this->stop&&this

8、->tasks.empty())return;task=std::move(this->tasks.front());this->tasks.pop();}task();}});}//addnewworkitemtothepooltemplateautoThreadPool::enqueue(F&&f,Args&&...args)->std::future::type>{usingreturn_type=typenamestd::result_of

9、::type;autotask=std::make_shared>(std::bind(std::forward(f),std::forward(args)...));std::futureres=task->get_future();{std::unique_locklock(queue_mutex);//don'tallowenqueueingafterstoppingthepoolif(stop

10、)throwstd::runtime_error("

当前文档最多预览五页,下载文档查看全文

此文档下载收益归作者所有

当前文档最多预览五页,下载文档查看全文
温馨提示:
1. 部分包含数学公式或PPT动画的文件,查看预览时可能会显示错乱或异常,文件下载后无此问题,请放心下载。
2. 本文档由用户上传,版权归属用户,天天文库负责整理代发布。如果您对本文档版权有争议请及时联系客服。
3. 下载前请仔细阅读文档内容,确认文档内容符合您的需求后进行下载,若出现内容与标题不符可向本站投诉处理。
4. 下载文档时可能由于网络波动等原因无法下载或下载错误,付费完成后未能成功下载的用户请联系客服处理。