Checkpointing work on first-pass implementation
This commit is contained in:
@@ -5,15 +5,27 @@
|
|||||||
#include <vector>
|
#include <vector>
|
||||||
#include <memory>
|
#include <memory>
|
||||||
#include <condition_variable>
|
#include <condition_variable>
|
||||||
|
#include <future>
|
||||||
|
#include <deque>
|
||||||
|
|
||||||
namespace daggy {
|
namespace daggy {
|
||||||
|
using AsyncTask = std::function<void()>;
|
||||||
class ThreadPool {
|
class ThreadPool {
|
||||||
public:
|
public:
|
||||||
ThreadPool(size_t nWorkers);
|
ThreadPool(size_t nWorkers);
|
||||||
|
~ThreadPool();
|
||||||
|
|
||||||
|
ThreadPool(const ThreadPool & other) = delete;
|
||||||
|
ThreadPool(ThreadPool & other) = delete;
|
||||||
|
|
||||||
|
void shutdown();
|
||||||
|
|
||||||
|
std::future<void> addTask(AsyncTask fn);
|
||||||
private:
|
private:
|
||||||
std::atomic<bool> shutdown_;
|
std::atomic<bool> shutdown_;
|
||||||
std::mutex guard_;
|
std::mutex guard_;
|
||||||
std::condition_variable cv_;
|
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
44
daggy/src/ThreadPool.cpp
Normal 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();
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user