diff --git a/services/lib/src/Worker.h b/services/lib/src/Worker.h new file mode 100644 --- /dev/null +++ b/services/lib/src/Worker.h @@ -0,0 +1,46 @@ +#pragma once + +#include +#include +#include +#include +#include + +typedef std::function Task; +typedef std::function)> Callback; + +class Worker { + std::vector threads; + std::mutex threadsMutex; + std::atomic currentId = 0; + + Worker() {} + + virtual ~Worker() { + const std::lock_guard lock(this->threadsMutex); + for (auto &thread : this-> threads) { + thread.join(); + } + } +public: + + static Worker &getInstance() { + static Worker instance; + return instance; + } + + void schedule(Task task, Callback callback) { + size_t id = this->currentId++; + std::thread t([](size_t id, Task task, Callback callback) { + std::unique_ptr err = nullptr; + try { + task(); + } catch (std::exception &e) { + err = std::make_unique(e.what()); + } + callback(std::move(err)); + }, id, std::move(task), std::move(callback)); + const std::lock_guard lock(this->threadsMutex); + this->threads.push_back(std::move(t)); + } +};