Waybar/include/util/chrono.hpp

90 lines
1.5 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>
2018-08-19 11:39:57 +00:00
#include <gtkmm.h>
2018-08-08 21:54:58 +00:00
namespace waybar::chrono {
using namespace std::chrono;
2018-08-08 21:54:58 +00:00
using clock = std::chrono::system_clock;
using duration = clock::duration;
using time_point = std::chrono::time_point<clock, duration>;
2018-08-08 21:54:58 +00:00
}
namespace waybar::util {
struct SleeperThread {
SleeperThread() = default;
2018-08-08 21:54:58 +00:00
SleeperThread(std::function<void()> func)
2018-08-19 11:39:57 +00:00
: thread_{[this, func] {
while(true) {
{
std::lock_guard<std::mutex> lock(mutex_);
if (!do_run_) {
break;
}
}
2018-08-08 21:54:58 +00:00
func();
2018-08-19 11:39:57 +00:00
}
}}
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] {
while(true) {
{
std::lock_guard<std::mutex> lock(mutex_);
if (!do_run_) {
break;
}
}
func();
2018-08-19 11:39:57 +00:00
}
});
return *this;
}
auto sleep_for(chrono::duration dur)
{
2018-08-19 11:39:57 +00:00
auto lock = std::unique_lock(mutex_);
return condvar_.wait_for(lock, dur);
}
auto sleep_until(chrono::time_point time)
{
2018-08-19 11:39:57 +00:00
auto lock = std::unique_lock(mutex_);
return condvar_.wait_until(lock, time);
}
auto wake_up()
{
2018-08-19 11:39:57 +00:00
condvar_.notify_all();
}
~SleeperThread()
{
2018-08-19 11:39:57 +00:00
do_run_ = false;
condvar_.notify_all();
2018-08-29 19:07:58 +00:00
if (thread_.joinable()) {
thread_.detach();
}
}
private:
2018-08-19 11:39:57 +00:00
std::thread thread_;
std::condition_variable condvar_;
std::mutex mutex_;
bool do_run_ = true;
};
2018-08-08 21:54:58 +00:00
}