Скажите правильно ли я написал thread_pool. Особенно функцию Post и ее return
#include <iostream>
#include<future>
#include<queue>
#include<thread>
#include<condition_variable>
class SimpleThreadPool {
public:
explicit SimpleThreadPool(std::size_t threadCount=std::thread::hardware_concurrency());
~SimpleThreadPool();
SimpleThreadPool(const SimpleThreadPool& ) = delete;
SimpleThreadPool& operator = (const SimpleThreadPool& ) = delete;
template<typename Fnc_T>
auto Post(Fnc_T&& task)->std::future<decltype(task())> ;
void WorkOn();
void Destroy();
private:
size_t m_threadCount;
std::vector<std::thread> m_threads;
std::queue<std::function<void()>> m_tasks;
std::condition_variable m_condition;
std::mutex m_mut;
bool m_stop;
bool m_emergencyStop;
};
SimpleThreadPool::SimpleThreadPool(std::size_t threadCount): m_threadCount(threadCount), m_stop(false), m_emergencyStop(false){
if (m_threadCount == 0)
throw std::runtime_error("ERROR: Thread::Pool() -- must have at least one thread");
m_threads.reserve(m_threadCount);
for (std::size_t i = 0; i < m_threadCount; ++i)
m_threads.emplace_back([this]() { WorkOn(); });
}
SimpleThreadPool::~SimpleThreadPool()
{
{
std::unique_lock<std::mutex> queue_lock(m_mut);
m_stop = true;
}
m_condition.notify_all();
for (auto& task_thread : m_threads)
task_thread.join();
}
void SimpleThreadPool::WorkOn()
{
while (true)
{
std::function<void()> task;
{
std::unique_lock<std::mutex> queue_lock(m_mut);
m_condition.wait
(
queue_lock,
[this]() { return !m_tasks.empty() || m_stop || m_emergencyStop; }
);
if ((m_tasks.empty() && m_stop)|| m_emergencyStop)
return;
task = std::move(m_tasks.front());
m_tasks.pop();
}
task();
}
}
template<typename Fnc_T>
auto SimpleThreadPool::Post(Fnc_T&& task) -> std::future<decltype(task())>
{
{
std::unique_lock<std::mutex>lock(m_mut);
if (m_stop || m_emergencyStop)
throw std::runtime_error("ERROR: Thread::Pool::Add_Task() - attempted to add task to stopped pool");
m_tasks.emplace(std::forward<Fnc_T>(task));
}
m_condition.notify_one();
return std::packaged_task<decltype(task())>(task).get_future();
}
void SimpleThreadPool::Destroy()
{
{
std::unique_lock<std::mutex> queue_lock(m_mut);
m_emergencyStop = true;
}
m_condition.notify_all();
for (auto& task_thread : m_threads)
task_thread.join();
}
Есть такой код. Скажите правильно ли будет он работать, особенно я не уверен у функции Post потому што не уверен, што возвращаю коректное значение.