简单的C++11线程池实现
线程池的C++11简单实现,源代码来自Github上作者progschj,地址为:A simple C++11 Thread Pool implementation,具体博客可以参见Jakob’s Devlog,地址为:A Thread Pool with C++11
1、线程池的实现代码如下:
ThreadPool.h
#ifndef THREAD_POOL_H
#define THREAD_POOL_H
#include <vector>
#include <queue>
#include <memory>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <future>
#include <functional>
#include <stdexcept>
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:
// need to keep track of threads so we can join them
std::vector< std::thread > workers;
// the task queue
std::queue< std::function<void()> > tasks;
// synchronization
std::mutex queue_mutex;
std::condition_variable condition;
bool stop;
};
// the constructor just launches some amount of workers
inline ThreadPool::ThreadPool(size_t threads)
: stop(false)
{
for(size_t i = 0;i<threads;++i)
workers.emplace_back(
[this]
{
for(;;)
{
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();
}
}
);
}
// add new work item to the pool
template<class F, class... Args>
auto ThreadPool::enqueue(F&& f, Args&&... args)
-> std::future<typename std::result_of<F(Args...)>::type>
{
using return_type = typename std::result_of<F(Args...)>::type;
auto task = std::make_shared< std::packaged_task<return_type()> >(
std::bind(std::forward<F>(f), std::forward<Args>(args)...)
);
std::future<return_type> res = task->get_future();
{
std::unique_lock<std::mutex> lock(queue_mutex);
// don't allow enqueueing after stopping the pool
if(stop)
throw std::runtime_error("enqueue on stopped ThreadPool");
tasks.emplace([task](){ (*task)(); });
}
condition.notify_one();
return res;
}
// the destructor joins all threads
inline ThreadPool::~ThreadPool()
{
{
std::unique_lock<std::mutex> lock(queue_mutex);
stop = true;
}
condition.notify_all();
for(std::thread &worker: workers)
worker.join();
}
#endif
2、基本的用法:
// create thread pool with 4 worker threads
ThreadPool pool(4);
// enqueue and store future
auto result = pool.enqueue([](int answer) { return answer; }, 42);
// get result from future
std::cout << result.get() << std::endl;
3、测试C++11线程池的例子程序如下:
example.cpp
#include <iostream>
#include <vector>
#include <chrono>
#include "ThreadPool.h"
int main()
{
ThreadPool pool(4);
std::vector< std::future<int> > results;
for(int i = 0; i < 8; ++i) {
results.emplace_back(
pool.enqueue([i] {
std::cout << "hello " << i << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "world " << i << std::endl;
return i*i;
})
);
}
for(auto && result: results)
std::cout << result.get() << ' ';
std::cout << std::endl;
return 0;
}
编译运行example.cpp时需要添加C++11的支持,并且要加入pthread库的链接。
在Linux下的编译的命令为: g++ example.cpp -o example -std=c++11 -lpthread;如果在VS2017中使用,由于默认支持C++11,可以直接创建一个控制台程序,添加ThreadPool.h和example.cpp到项目,编译运行即可。
在Ubuntu18.10下测试如下:
havealex@havealex:~/GithubProjects/ThreadPool$ ls
COPYING example.cpp README.md ThreadPool.h
havealex@havealex:~/GithubProjects/ThreadPool$ g++ example.cpp -o example -std=c++11
/usr/bin/ld: /tmp/ccduRGse.o: in function `std::thread::thread<ThreadPool::ThreadPool(unsigned long)::{lambda()#1}, , void>(ThreadPool::ThreadPool(unsigned long)::{lambda()#1}&&)':
example.cpp:(.text._ZNSt6threadC2IZN10ThreadPoolC4EmEUlvE_JEvEEOT_DpOT0_[_ZNSt6threadC5IZN10ThreadPoolC4EmEUlvE_JEvEEOT_DpOT0_]+0x2f): undefined reference to `pthread_create'
collect2: error: ld returned 1 exit status
havealex@havealex:~/GithubProjects/ThreadPool$ g++ example.cpp -o example -std=c++11 -lpthread
havealex@havealex:~/GithubProjects/ThreadPool$ ls\
> ^C
havealex@havealex:~/GithubProjects/ThreadPool$ ls
COPYING example example.cpp README.md ThreadPool.h
havealex@havealex:~/GithubProjects/ThreadPool$ ./example
hello 0
hello 1
hello 2
hello 3
world 1
hello 4
world 0
hello 5
0 1 world 2
hello 6
4 world 3
hello 7
9 world 5
world 4
16 25 world 6
36 world 7
49
可以看出,结果的输出是无序并行的。
简单的C++11线程池实现的更多相关文章
- 托管C++线程锁实现 c++11线程池
托管C++线程锁实现 最近由于工作需要,开始写托管C++,由于C++11中的mutex,和future等类,托管C++不让调用(报错),所以自己实现了托管C++的线程锁. 该类可确保当一个线程位于 ...
- c++11线程池实现
咳咳.c++11 增加了线程库,从此告别了标准库不支持并发的历史. 然而 c++ 对于多线程的支持还是比較低级,略微高级一点的使用方法都须要自己去实现,譬如线程池.信号量等. 线程池(thread p ...
- c++ 11 线程池---完全使用c++ 11新特性
前言: 目前网上的c++线程池资源多是使用老版本或者使用系统接口实现,使用c++ 11新特性的不多,最近研究了一下,实现一个简单版本,可实现任意任意参数函数的调用以及获得返回值. 0 前置知识 首先介 ...
- c++11 线程池学习笔记 (一) 任务队列
学习内容来自一下地址 http://www.cnblogs.com/qicosmos/p/4772486.html github https://github.com/qicosmos/cosmos ...
- C++11线程池的实现
什么是线程池 处理大量并发任务,一个请求一个线程来处理请求任务,大量的线程创建和销毁将过多的消耗系统资源,还增加了线程上下文切换开销. 线程池通过在系统中预先创建一定数量的线程,当任务请求到来时从线程 ...
- Linux下简单的多线程编程--线程池的实现
/* 写在前面的话: 今天刚“开原”,选择了一篇关于线程池的文件与大家分享,希望能对您学习有所帮助,也希望能与大家共同学习! 选择在这个特殊的时候注册并发文章也是有一些我个人特殊的意义的,看我的id( ...
- 简单明了的Java线程池
线程池 线程池从功能上来看,就是一个任务管理器.在Java中,Executor接口是线程池的根接口,其中只包含一个方法: Executor void execute(Runnable command) ...
- 基于C++11线程池
1.包装线程对象 class task : public std::tr1::enable_shared_from_this<task> { public: task():exit_(fa ...
- 简单RPC框架-业务线程池
*:first-child { margin-top: 0 !important; } body>*:last-child { margin-bottom: 0 !important; } /* ...
随机推荐
- CSS3实现小于1px的边框(移动端)
<!doctype html> <html lang="en"> <head> <meta content="width=dev ...
- grunt默认只允许localhost和访问,如何设置外部IP地址访问
转载请注明出处: 猩猩队长 http://www.cnblogs.com/wayns/p/access_grunt_server_from_outside.html 使用Yeoman生成器创建web ...
- win32 socket 编程(一)——TCP/IP
一.基本概念 a) 同步:指发送方发出数据后,等收到接收方发回的响应,才发下一个数据包的通信方式. nb)异步:指的是发送方不等接收方响应,便接着发下个数据包的通信方式. c) 阻塞:指调用某函数时, ...
- 全面优化MySQL(一)
mysql执行一条查询语句的内部执行过程 权限验证 客户端通过连接器连接到 MYSQL服务器. 查询缓存 查询是否有查询缓存, 如果有缓存(之前执行过此语句),则直接返回缓存数据. 语法检查 分析器会 ...
- Object中有哪些公用方法?
clone()方法 实现对象的浅复制,只有实现了Cloneable接口才能调用该方法. toString()方法 返回该对象的字符串表示. equals()方法: 在Object中与“==”的定义是一 ...
- ps:不规则选区
尽管我们学会了如何添加减去或是交叉选区,但选取出来的选区还是比较规则,不是矩形就是圆形,这样的形状很难胜任在实际制作中的需要.现在我们就要学习如何建立一个任意形状的选区.建立任意选区的工具是套索工具. ...
- php内置函数分析之strrev()
PHP_FUNCTION(strrev) { zend_string *str; char *e, *p; zend_string *n; if (zend_parse_parameters(ZEND ...
- 前端每日实战:32# 视频演示如何用纯 CSS 创作六边形按钮特效
效果预览 按下右侧的"点击预览"按钮可以在当前页面预览,点击链接可以全屏预览. https://codepen.io/comehope/pen/xjoOeM 可交互视频教程 此视频 ...
- Prometheus + Node Exporter + Grafana 监控主机运行信息
上一篇文章中讲了如何利用Prometheus和Grafana监控SpringBoot应用的JVM信息,这次就来看看如何监控 服务器运行状态,先列出用到的工具: Prometheus node_ex ...
- list列表切片方法汇总
python为list列表提供了强大的切片功能,下面是一些常见功能的汇总 """ 使用模式: [start:end:step] 其中start表示切片开始的位置,默认是0 ...