This repository has been archived on 2022-02-10. You can view files and clone it, but cannot push or open issues or pull requests.
fortuna/do_task.cpp
surtur b7c7558e1f
All checks were successful
continuous-integration/drone/push Build is passing
DoTask: timed_mutex -> recursive_timed_mutex
2022-01-21 02:54:15 +01:00

42 lines
731 B
C++

#ifndef FORTUNA_DO_TASK_CPP
#define FORTUNA_DO_TASK_CPP
#include "do_task.h"
#include <utility>
namespace fortuna {
auto DoTask::die_pls() -> void {
mtx_do_sleep.unlock();
th.join();
}
auto DoTask::thread_pls(const std::chrono::seconds& interval,
std::function<void()> callback) -> void {
if (th.joinable()) {
die_pls();
}
// since this is a std::recursive_timed_mutex, an attempt is made to only
// try_lock() it
mtx_do_sleep.try_lock();
th = std::thread([this, interval, callback = std::move(callback)] {
while (!mtx_do_sleep.try_lock_for(interval)) {
callback();
}
});
}
DoTask::~DoTask() noexcept {
if (th.joinable()) {
die_pls();
}
}
} // namespace fortuna
#endif // FORTUNA_DO_TASK_CPP