简单的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; } /* ...
随机推荐
- ofbiz idea 启动
1.下载gradle并安装到本地 2.idea引入gradle 3.gradle右键选择refresh,项目会重新编译并加载gradle的task 4.可以再编译一下 5.没问题的话打开,jar ap ...
- atomic,nonatomic
atomic和nonatomic用来决定编译器生成的getter和setter是否为原子操作. atomic 设置成员变量的@property属性时,默认为atomic,提供多线程安全 ...
- 【转载】JDK8 特性 stream(),lambda表达式,
Stream()表达式 虽然大部分情况下stream是容器调用Collection.stream()方法得到的,但stream和collections有以下不同: 无存储.stream不是一种数据结构 ...
- 搭建Keepalived+LNMP架构web动态博客 实现高可用与负载均衡
环境准备: 192.168.193.80 node1 192.168.193.81 node2 关闭防火墙 [root@node1 ~]# systemctl stop firewalld #两台都 ...
- Spring_搭建过程中遇到的问题
先看一下问题: 1.在web.xml中配置Spring 加载Spring mvc的时候配置如下: <!--配置SpringMVC的前端控制器--> <servlet> < ...
- ps:图像尺寸
在课程#01中我们知道了显示器上的图像是由许多点构成的,这些点称为像素,意思就是“构成图像的元素”.但是要明白一点:像素作为图像的一种尺寸,只存在于电脑中,如同RGB色彩模式一样只存在于电脑中.像素是 ...
- css图像拼合技术(精灵图)
CSS图像拼合技术 1.图像拼合 图像拼合技术就是单个图像的集合. 有很多图片的网页可能会需要很多时间来加载和生成多个服务器的请求. 使用图像拼合会降低服务器的请求数量,并节省带宽. 图像拼合实例 有 ...
- BZOJ 3729 GTY的游戏
伪ETT? 貌似就是Splay维护dfn = = 我们首先观察这个博弈 这个博弈直接%(l+1)应该还是很显然的 因为先手怎么操作后手一定能保证操作总数取到(l+1) 于是就变成阶梯Nim了 因为对于 ...
- 【GMOJ6377】幽曲[埋骨于弘川]
Description \(n\in[1,500],k\in[2,10]\). Solution 这是一道有点很有难度的题. 先考虑判断一个数是否在数列\(a\)中.由于每次加的数是在\([0,k)\ ...
- [CF1166C]A Tale of Two Lands题解
比赛的时候lowerbound用错了 现场WA on test4(好吧我承认我那份代码确实有除了lowerbound以外的问题) 于是只能手动二分 (我好菜啊QAQ 经过一波数学推算,我们发现,设序列 ...