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

42 lines
731 B
C++
Raw Normal View History

#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,
2022-01-10 04:25:03 +01:00
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();
}
}
2022-01-10 04:25:03 +01:00
} // namespace fortuna
2022-01-10 04:25:03 +01:00
#endif // FORTUNA_DO_TASK_CPP