任务并行中线程池的研究
1.先参考下一个不错的C11线程池模板
#pragma once
#include <vector>
#include <queue>
#include <memory>
#include <thread>
#include <mutex>
#include <atomic>
#include <condition_variable>
#include <future>
#include <functional>
#include <stdexcept>
class ThreadPool
{
std::vector<std::thread> workers;
std::queue<std::function<void()>> tasks;
std::mutex queMutex;
std::condition_variable condition;
std::atomic_bool bStop;
public:
ThreadPool(size_t threads): bStop(false)
{
for (size_t i = 1; i <= threads; i++)
{
workers.emplace_back([this]
{
while (!bStop)
{
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(this->queMutex);
this->condition.wait(lock, [this] {
return this->bStop || !this->tasks.empty(); });
if (this->bStop && this->tasks.empty())
return;
task = std::move(this->tasks.front());
this->tasks.pop();
}
task();
}
} );
}
};
~ThreadPool()
{
{
std::unique_lock<std::mutex> lock(queMutex);
bStop = true;
}
condition.notify_all();
for (std::thread& worker