diff --git a/RayTracer/tools/Threadpool.cpp b/RayTracer/tools/Threadpool.cpp new file mode 100644 index 0000000000000000000000000000000000000000..be0075c082347cb139473df9b2b9776ccc3e946f --- /dev/null +++ b/RayTracer/tools/Threadpool.cpp @@ -0,0 +1,44 @@ +#include "Threadpool.h" + +namespace util { + +Threadpool::Threadpool(size_t n) : alive(true) { + // Create the specified number of threads + threads.reserve(n); + for (int i = 0; i < n; ++i) { + threads.emplace_back(std::bind(&Threadpool::threading, this, i)); + } +} + +Threadpool::~Threadpool() { + // std::unique_lock<std::mutex> lock(m); + + alive = false; + cv.notify_all(); + + for (auto &thread : threads) thread.join(); +} + +void Threadpool::queueTask(std::function<void(void)> task) { + std::unique_lock<std::mutex> lock(m); + q.emplace(task); + lock.unlock(); + cv.notify_one(); +} + +void Threadpool::threading(int i) { + while (true) { + std::unique_lock<std::mutex> lock(m); + while (alive && q.empty()) { + cv.wait(lock); + } + if (q.empty()) { + return; + } + auto task = std::move(q.front()); + q.pop(); + lock.unlock(); + task(); + } +} +} // namespace util diff --git a/RayTracer/tools/Threadpool.h b/RayTracer/tools/Threadpool.h new file mode 100644 index 0000000000000000000000000000000000000000..9bdea12f83bbdb97ae567271df5f100515fc789a --- /dev/null +++ b/RayTracer/tools/Threadpool.h @@ -0,0 +1,28 @@ +#include <condition_variable> +#include <functional> +#include <iostream> +#include <mutex> +#include <queue> +#include <thread> + +namespace util { + +class Threadpool { + public: + // Constructor, Destructor + Threadpool(size_t n); + ~Threadpool(); + // Add a task to the queue + void queueTask(std::function<void(void)> task); + + protected: + void threading(int i); + + private: + std::vector<std::thread> threads; + bool alive; + std::queue<std::function<void(void)>> q; + std::condition_variable cv; + std::mutex m; +}; +} // namespace util \ No newline at end of file