22 for (
size_t i = 0; i < size; ++i)
23 _threads.emplace_back([
this] { this->work(); });
29 std::unique_lock<std::mutex> lock(_mutex);
31 _condition.notify_all();
38 return _threads.size();
44 using ReturnType =
typename std::result_of<F()>::type;
47 std::make_shared<std::packaged_task<ReturnType()> >(std::forward<F>(f));
49 auto res = task->get_future();
51 std::unique_lock<std::mutex> lock(_mutex);
52 _tasks.emplace([task]() { (*task)(); });
54 _condition.notify_one();
62 std::unique_lock<std::mutex> lock(_mutex);
65 _condition.notify_one();
70 std::unique_lock<std::mutex> lock(_mutex);
71 return !_tasks.empty();
74 void ThreadPool::joinAll()
76 for (
auto& thread : _threads)
80 void ThreadPool::work()
84 std::function<void()> task;
86 std::unique_lock<std::mutex> lock(_mutex);
87 _condition.wait(lock, [
this] {
return _stop || !_tasks.empty(); });
90 task = std::move(_tasks.front());
bool hasPendingJobs() const
~ThreadPool()
Destroy this thread pool.
std::future< typename std::result_of< F()>::type > post(F &&f)
Post a new task in the thread pool.
ThreadPool(const size_t size=std::max(1u, std::thread::hardware_concurrency()))
Construct a ThreadPool.
void postDetached(F &&f)
Post a detached task in the thread pool.
Abstraction layer and common utilities for multi-threaded programming.