Waybar/include/util/sleeper_thread.hpp

83 lines
1.4 KiB
C++
Raw Normal View History

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