https://github.com/progschj/ThreadPool/
c++ 线程池实现学习和分析
(1条消息) c++11线程池实现_zdarks的专栏-CSDN博客_c++线程池
// 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();
}
}
);
}
创建workers (及对应参数数量的线程)
往workers中存入lambada函数
函数是一个死循环,从tasks中取出一个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;
}
往线程池中加入task
总之就是一些很奇特的语法啦,
我的paecs库里也有相关类似的操作,将system的函数指针以及参数信息存起来,放到以后调用
paecs/Scene.h at main · ActivePeter/paecs (github.com)
以后改进的时候可以参考一下这个线程池实现,我对c++的语法了解还是太少了。