12 Star 23 Fork 8

caipengyang / esvr

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
es_thread_pool.h 2.13 KB
一键复制 编辑 原始数据 按行查看 历史
caipengyang 提交于 2016-04-15 11:31 . fix bug
//
// Created by Administrator on 2015/5/26.
//
#pragma once
#include <vector>
#include <queue>
#include <mutex>
#include <thread>
#include <future>
#include <functional>
#include <condition_variable>
namespace esvr
{
class ThreadPool{
public:
ThreadPool(size_t);
~ThreadPool();
template<typename F, typename... Args>
auto enqueue(F&& f, Args&&... args)->std::future < typename std::result_of<F(Args...)>::type > ;
void destroy();
private:
std::vector<std::thread> workers;
std::queue<std::function<void()>> tasks;
private:
std::mutex queue_mutex;
std::condition_variable condition;
volatile bool stop{ false };
};
inline ThreadPool::ThreadPool(size_t threads)
{
threads = threads < 2 ? 2 : threads;
for (size_t i = 0; i < threads; ++i)
{
workers.emplace_back(std::thread(
[this]
{
for (; !this->stop;)
{
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(queue_mutex);
this->condition.wait(lock, [this]{return this->stop || !this->tasks.empty(); });
if (this->stop && this->tasks.empty()) break;
task = std::move(this->tasks.front());
this->tasks.pop();
}
task();
}
}
)
);
}
}
template<typename F, typename... 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);
if (!stop) tasks.emplace([task](){(*task)(); });
}
condition.notify_one();
return res;
}
inline ThreadPool::~ThreadPool()
{
this->destroy();
}
void ThreadPool::destroy()
{
{
//std::unique_lock<std::mutex> lock(queue_mutex); msvc2013 dead lock.
if (stop) return;
stop = true;
}
condition.notify_all();
for (auto& worker : workers)
{
if (worker.joinable()) worker.join();
}
workers.clear();
std::this_thread::sleep_for(std::chrono::microseconds(100));
}
};
C++
1
https://gitee.com/caipengyang/esvr.git
git@gitee.com:caipengyang/esvr.git
caipengyang
esvr
esvr
master

搜索帮助