File: sleeper_thread.hpp

package info (click to toggle)
waybar 0.15.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,464 kB
  • sloc: cpp: 25,331; xml: 742; python: 146; ansic: 77; makefile: 29
file content (126 lines) | stat: -rw-r--r-- 3,133 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#pragma once

#include <chrono>
#include <condition_variable>
#include <ctime>
#include <functional>
#include <thread>

#include "prepare_for_sleep.h"

namespace waybar::util {

/**
 * Defer pthread_cancel until the end of a current scope.
 *
 * Required to protect a scope where it's unsafe to raise `__forced_unwind` exception.
 * An example of these is a call of a method marked as `noexcept`; an attempt to cancel within such
 * a method may result in a `std::terminate` call.
 */
class CancellationGuard {
  int oldstate;

 public:
  CancellationGuard() { pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldstate); }
  ~CancellationGuard() { pthread_setcancelstate(oldstate, &oldstate); }
};

class SleeperThread {
 public:
  SleeperThread() = default;

  SleeperThread(std::function<void()> func)
      : thread_{[this, func] {
          while (do_run_) {
            signal_ = false;
            func();
          }
        }} {
    connection_ = prepare_for_sleep().connect([this](bool sleep) {
      if (not sleep) wake_up();
    });
  }

  SleeperThread& operator=(std::function<void()> func) {
    thread_ = std::thread([this, func] {
      while (do_run_) {
        signal_ = false;
        func();
      }
    });
    if (connection_.empty()) {
      connection_ = prepare_for_sleep().connect([this](bool sleep) {
        if (not sleep) wake_up();
      });
    }
    return *this;
  }

  bool isRunning() const { return do_run_; }

  auto sleep() {
    std::unique_lock lk(mutex_);
    CancellationGuard cancel_lock;
    return condvar_.wait(lk, [this] { return signal_ || !do_run_; });
  }

  auto sleep_for(std::chrono::system_clock::duration dur) {
    std::unique_lock lk(mutex_);
    CancellationGuard cancel_lock;
    constexpr auto max_time_point = std::chrono::steady_clock::time_point::max();
    auto wait_end = max_time_point;
    auto now = std::chrono::steady_clock::now();
    if (now < max_time_point - dur) {
      wait_end = now + dur;
    }
    return condvar_.wait_until(lk, wait_end, [this] { return signal_ || !do_run_; });
  }

  auto sleep_until(
      std::chrono::time_point<std::chrono::system_clock, std::chrono::system_clock::duration>
          time_point) {
    std::unique_lock lk(mutex_);
    CancellationGuard cancel_lock;
    return condvar_.wait_until(lk, time_point, [this] { return signal_ || !do_run_; });
  }

  void wake_up() {
    {
      std::lock_guard<std::mutex> lck(mutex_);
      signal_ = true;
    }
    condvar_.notify_all();
  }

  auto stop() {
    {
      std::lock_guard<std::mutex> lck(mutex_);
      signal_ = true;
      do_run_ = false;
    }
    condvar_.notify_all();
    auto handle = thread_.native_handle();
    if (handle != 0) {
      // TODO: find a proper way to terminate thread...
      pthread_cancel(handle);
    }
  }

  ~SleeperThread() {
    connection_.disconnect();
    stop();
    if (thread_.joinable()) {
      thread_.join();
    }
  }

 private:
  std::thread thread_;
  std::condition_variable condvar_;
  std::mutex mutex_;
  bool do_run_ = true;
  bool signal_ = false;
  sigc::connection connection_;
};

}  // namespace waybar::util