I have made a thread pool which will dynamically create threads based on how many you need.
#pragma once
#include <thread>
#include <atomic>
#include <mutex>
#include <vector>
#include <functional>
#include <condition_variable>
class thread_pool {
public:
thread_pool() : stop(false), busy_workers(0) { }
~thread_pool() {
stop = true;
task_available.notify_all();
for (auto& worker : workers) {
if (worker.joinable()) {
worker.join();
}
}
}
void run_task(std::function<void()> task) {
{
std::lock_guard<std::mutex> task_lock{ task_mu };
current_task = std::move(task);
}
{
std::lock_guard<std::mutex> workers_lock{ workers_mu };
if (workers.size() == busy_workers++) {
workers.emplace_back(work);
return;
}
}
task_available.notify_one();
}
private:
std::atomic_bool stop;
std::atomic_size_t busy_workers;
std::vector<std::thread> workers;
std::function<void()> current_task;
std::condition_variable task_available;
std::mutex task_mu;
std::mutex workers_mu;
std::function<void()> work = [&]() {
while (true) {
std::unique_lock<std::mutex> task_lock{ task_mu };
task_available.wait(task_lock, [&]() { return current_task || stop; });
if (!current_task && stop) return;
auto task = std::move(current_task);
task_lock.unlock();
task();
busy_workers--;
}
};
};
The only problem I have with it is the threads will be destroyed before all the tasks have been completed, even though I join all the threads in the destructor.