waybar/include/util/sleeper_thread.hpp

80 lines
1.6 KiB
C++
Raw Normal View History

2018-08-08 23:54:58 +02:00
#pragma once
#include <chrono>
2019-04-18 17:52:00 +02:00
#include <condition_variable>
2018-08-08 23:54:58 +02:00
#include <ctime>
#include <functional>
#include <thread>
namespace waybar::util {
2018-12-26 11:13:36 +01:00
class SleeperThread {
2019-04-18 17:52:00 +02:00
public:
SleeperThread() = default;
2018-08-08 23:54:58 +02:00
SleeperThread(std::function<void()> func)
2019-04-18 17:52:00 +02:00
: thread_{[this, func] {
2019-06-11 22:09:47 +02:00
while (do_run_) {
signal_ = false;
func();
}
2019-04-18 17:52:00 +02:00
}} {}
2019-04-18 17:52:00 +02:00
SleeperThread& operator=(std::function<void()> func) {
2018-08-19 13:39:57 +02:00
thread_ = std::thread([this, func] {
2019-03-18 18:46:44 +01:00
while (do_run_) {
signal_ = false;
func();
}
});
return *this;
}
2019-04-18 17:52:00 +02:00
bool isRunning() const { return do_run_; }
2019-04-18 17:52:00 +02:00
auto sleep_for(std::chrono::system_clock::duration dur) {
2018-12-26 11:13:36 +01:00
std::unique_lock lk(mutex_);
2019-03-18 18:46:44 +01:00
return condvar_.wait_for(lk, dur, [this] { return signal_ || !do_run_; });
}
2019-04-18 17:52:00 +02:00
auto sleep_until(
std::chrono::time_point<std::chrono::system_clock, std::chrono::system_clock::duration>
time_point) {
2018-12-26 11:13:36 +01:00
std::unique_lock lk(mutex_);
2019-03-18 18:46:44 +01:00
return condvar_.wait_until(lk, time_point, [this] { return signal_ || !do_run_; });
}
2019-04-18 17:52:00 +02:00
auto wake_up() {
2019-06-11 22:09:47 +02:00
{
std::lock_guard<std::mutex> lck(mutex_);
signal_ = true;
}
2018-08-19 13:39:57 +02:00
condvar_.notify_all();
}
2019-04-18 17:52:00 +02:00
auto stop() {
2018-12-26 11:13:36 +01:00
{
std::lock_guard<std::mutex> lck(mutex_);
2019-03-18 18:46:44 +01:00
signal_ = true;
2018-12-26 11:13:36 +01:00
do_run_ = false;
}
2018-08-19 13:39:57 +02:00
condvar_.notify_all();
}
2019-04-18 17:52:00 +02:00
~SleeperThread() {
2018-09-18 23:15:37 +02:00
stop();
2018-12-18 17:30:54 +01:00
if (thread_.joinable()) {
2018-12-26 11:13:36 +01:00
thread_.join();
2018-12-18 17:30:54 +01:00
}
2018-09-18 23:15:37 +02:00
}
2019-04-18 17:52:00 +02:00
private:
std::thread thread_;
2018-08-19 13:39:57 +02:00
std::condition_variable condvar_;
2019-04-18 17:52:00 +02:00
std::mutex mutex_;
bool do_run_ = true;
bool signal_ = false;
};
2018-08-08 23:54:58 +02:00
2019-04-18 17:52:00 +02:00
} // namespace waybar::util