File tree Expand file tree Collapse file tree 3 files changed +126
-0
lines changed
Expand file tree Collapse file tree 3 files changed +126
-0
lines changed Original file line number Diff line number Diff line change 1+ # SYNOPSIS
2+ Simple timeouts for C++
3+
4+ # USAGE
5+
6+ ## CONSTRUCTOR
7+ ``` cpp
8+ Timeout t;
9+ ```
10+
11+ ## METHODS
12+
13+ ### set(lambda cb, int n)
14+ Set a timeout for n milliseconds
15+
16+ ``` cpp
17+ t.set([]() {
18+ cout << "ok, done";
19+ }, 100 * 10 );
20+ ```
21+
22+ ### sleep(int n)
23+ Go to sleep n for milliseconds
24+
25+ ``` cpp
26+ t.sleep(100 );
27+ ```
28+
29+ ### clear()
30+ Clear a timeout that has been set.
31+
32+ ``` cpp
33+ t.clear();
34+ ```
35+
Original file line number Diff line number Diff line change 1+ #ifndef TIMEOUT_H
2+ #define TIMEOUT_H
3+
4+ #include < mutex>
5+ #include < thread>
6+
7+ class Timeout {
8+
9+ typedef std::function<void ()> Callback;
10+
11+ Callback callback;
12+
13+ class {
14+
15+ bool clear = false ;
16+ struct escape {};
17+
18+ std::mutex mu;
19+ std::condition_variable con;
20+
21+ public:
22+
23+ void cancel () {
24+ std::unique_lock<std::mutex> lock (mu);
25+ clear = true ;
26+ con.notify_all ();
27+ }
28+
29+ void wait (int i) {
30+
31+ auto period = std::chrono::milliseconds (i);
32+ auto timedout = std::cv_status::no_timeout;
33+
34+ std::unique_lock<std::mutex> lock (mu);
35+
36+ if (clear || con.wait_for (lock, period) == timedout) {
37+ clear = false ;
38+ throw escape ();
39+ }
40+ }
41+ } clearable;
42+
43+ int ms = 0 ;
44+ int counter = 0 ;
45+
46+ std::unique_ptr<std::thread> th;
47+
48+ void loop () {
49+ try {
50+ while (true ) {
51+ if (++counter == ms) {
52+ clearable.cancel ();
53+ callback ();
54+ }
55+ clearable.wait (1 );
56+ }
57+ } catch (...) {
58+ return ;
59+ }
60+ }
61+
62+ public:
63+ void set (Callback cb, int i) {
64+ callback = cb;
65+ ms = i;
66+
67+ auto fn = std::bind (&Timeout::loop, this );
68+ auto t = new std::thread (fn);
69+
70+ th = std::unique_ptr<std::thread>(t);
71+ }
72+
73+ void clear () {
74+ clearable.cancel ();
75+ th->join ();
76+ }
77+
78+ void sleep (int n) {
79+ auto ms = std::chrono::milliseconds (n);
80+ std::this_thread::sleep_for (ms);
81+ }
82+ };
83+
84+ #endif
85+
Original file line number Diff line number Diff line change 1+ {
2+ "name" : " timeout" ,
3+ "verison" : " 1.0.0" ,
4+ "description" : " timeout functions" ,
5+ "url" : " //github.com/hij1nx/cpp-timeout"
6+ }
You can’t perform that action at this time.
0 commit comments