Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
parkpow
GitHub Repository: parkpow/deep-license-plate-recognition
Path: blob/master/cpp/linux/scheduler/InterruptableSleep.h
644 views
1
#pragma once
2
3
#include <chrono>
4
#include <thread>
5
#include <future>
6
#include <mutex>
7
#include <sstream>
8
9
namespace Bosma {
10
class InterruptableSleep {
11
12
using Clock = std::chrono::system_clock;
13
14
// InterruptableSleep offers a sleep that can be interrupted by any thread.
15
// It can be interrupted multiple times
16
// and be interrupted before any sleep is called (the sleep will immediately complete)
17
// Has same interface as condition_variables and futures, except with sleep instead of wait.
18
// For a given object, sleep can be called on multiple threads safely, but is not recommended as behaviour is undefined.
19
20
public:
21
InterruptableSleep() : interrupted(false) {
22
}
23
24
InterruptableSleep(const InterruptableSleep &) = delete;
25
26
InterruptableSleep(InterruptableSleep &&) noexcept = delete;
27
28
~InterruptableSleep() noexcept = default;
29
30
InterruptableSleep &operator=(const InterruptableSleep &) noexcept = delete;
31
32
InterruptableSleep &operator=(InterruptableSleep &&) noexcept = delete;
33
34
void sleep_for(Clock::duration duration) {
35
std::unique_lock<std::mutex> ul(m);
36
cv.wait_for(ul, duration, [this] { return interrupted; });
37
interrupted = false;
38
}
39
40
void sleep_until(Clock::time_point time) {
41
std::unique_lock<std::mutex> ul(m);
42
cv.wait_until(ul, time, [this] { return interrupted; });
43
interrupted = false;
44
}
45
46
void sleep() {
47
std::unique_lock<std::mutex> ul(m);
48
cv.wait(ul, [this] { return interrupted; });
49
interrupted = false;
50
}
51
52
void interrupt() {
53
std::lock_guard<std::mutex> lg(m);
54
interrupted = true;
55
cv.notify_one();
56
}
57
58
private:
59
bool interrupted;
60
std::mutex m;
61
std::condition_variable cv;
62
};
63
}
64
65