Skip to content
Snippets Groups Projects
Commit f2b403a8 authored by Yoel's avatar Yoel
Browse files

Added a threadpool class to the util namespace

parent bc30bcbd
No related branches found
No related tags found
No related merge requests found
#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
#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
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment