fortuna/do_task.cpp

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