9 Star 31 Fork 22

10km/common_source_cpp

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
ThreadPool.cpp 1.60 KB
一键复制 编辑 原始数据 按行查看 历史
/*
* ThreadPool.cpp
*
* Created on: 2015年11月24日
*/
#include "ThreadPool.h"
#include <chrono>
#include <stdexcept>
namespace gdface{
ThreadPool::ThreadPool(size_t concurrency, bool force)
: concurrency(concurrency),stop(false)
{
for(size_t i = 0;i<this->concurrency;++i)
workers.emplace_back(
[this]
{
for(;;)
{
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(this->queue_mutex);
this->condition.wait_for(lock, std::chrono::milliseconds(100),
[this] { return this->stop || !this->tasks.empty(); });
if (this->stop)
{
if (this->force)
return;
else if (this->tasks.empty())
return;
}
else if (this->tasks.empty())
continue;
task = std::move(this->tasks.front());
this->tasks.pop();
}
task();
}
}
);
}
// the destructor joins all threads
ThreadPool::~ThreadPool()
{
{
std::unique_lock<std::mutex> lock(queue_mutex);
stop = true;
}
// remove,because the code will cause deadlock while dynamic library unload
//condition.notify_all();
for(std::thread &worker: workers)
worker.join();
}
} /* namespace gdface */
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/l0km/common_source_cpp.git
git@gitee.com:l0km/common_source_cpp.git
l0km
common_source_cpp
common_source_cpp
master

搜索帮助