Checkpointing work on first-pass implementation

This commit is contained in:
Ian Roddis
2021-06-16 10:48:31 -03:00
parent a661125976
commit d871572d5e
2 changed files with 57 additions and 1 deletions

View File

@@ -5,15 +5,27 @@
#include <vector>
#include <memory>
#include <condition_variable>
#include <future>
#include <deque>
namespace daggy {
using AsyncTask = std::function<void()>;
class ThreadPool {
public:
ThreadPool(size_t nWorkers);
~ThreadPool();
ThreadPool(const ThreadPool & other) = delete;
ThreadPool(ThreadPool & other) = delete;
void shutdown();
std::future<void> addTask(AsyncTask fn);
private:
std::atomic<bool> shutdown_;
std::mutex guard_;
std::condition_variable cv_;
std::vector<std::thread> workers;
std::vector<std::thread> workers_;
std::deque<AsyncTask> taskQueue_;
};
}

44
daggy/src/ThreadPool.cpp Normal file
View File

@@ -0,0 +1,44 @@
#include <daggy/ThreadPool.hpp>
using namespace daggy;
ThreadPool::ThreadPool(size_t nWorkers) {
for (size_t i = 0; i < nWorkers; ++i) {
workers_.emplace_back([&]() {
while (true) {
AsyncTask tsk;
{
std::unique_lock<std::mutex> lk(guard_);
cv_.wait(lk, []{ return true; });
if (shutdown_) return;
tsk = taskQueue_.front();
taskQueue_.pop_front();
}
tsk();
}
});
}
}
ThreadPool::~ThreadPool() {
shutdown();
}
void ThreadPool::shutdown() {
shutdown_ = true;
cv_.notify_all();
for (auto & w : workers_) {
w.join();
}
}
std::future<void> ThreadPool::addTask(std::function<void()> fn) {
{
std::unique_lock<std::mutex> lk(guard_);
taskQueue_.push_back(fn);
}
cv_.notify_one();
}