]>
Commit | Line | Data |
---|---|---|
7c673cae FG |
1 | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- |
2 | // vim: ts=8 sw=2 smarttab | |
11fdf7f2 | 3 | |
7c673cae | 4 | /* |
31f18b77 | 5 | * Copyright (C) 2017 Red Hat Inc. |
11fdf7f2 TL |
6 | * |
7 | * Author: J. Eric Ivancich <ivancich@redhat.com> | |
8 | * | |
9 | * This is free software; you can redistribute it and/or modify it | |
10 | * under the terms of the GNU Lesser General Public License version | |
11 | * 2.1, as published by the Free Software Foundation. See file | |
12 | * COPYING. | |
7c673cae FG |
13 | */ |
14 | ||
15 | ||
16 | #pragma once | |
17 | ||
18 | #include <chrono> | |
19 | #include <mutex> | |
20 | #include <condition_variable> | |
21 | #include <thread> | |
22 | #include <functional> | |
23 | ||
11fdf7f2 | 24 | |
7c673cae FG |
25 | namespace crimson { |
26 | using std::chrono::duration_cast; | |
27 | using std::chrono::milliseconds; | |
28 | ||
29 | // runs a given simple function object waiting wait_period | |
30 | // milliseconds between; the destructor stops the other thread | |
31 | // immediately | |
32 | class RunEvery { | |
33 | using Lock = std::unique_lock<std::mutex>; | |
34 | using Guard = std::lock_guard<std::mutex>; | |
35 | using TimePoint = std::chrono::steady_clock::time_point; | |
36 | ||
37 | bool finishing = false; | |
38 | std::chrono::milliseconds wait_period; | |
39 | std::function<void()> body; | |
40 | std::mutex mtx; | |
41 | std::condition_variable cv; | |
42 | ||
43 | // put threads last so all other variables are initialized first | |
44 | ||
45 | std::thread thd; | |
46 | ||
47 | public: | |
48 | ||
49 | #ifdef ADD_MOVE_SEMANTICS | |
50 | RunEvery(); | |
51 | #endif | |
52 | ||
53 | template<typename D> | |
54 | RunEvery(D _wait_period, | |
11fdf7f2 | 55 | const std::function<void()>& _body) : |
7c673cae FG |
56 | wait_period(duration_cast<milliseconds>(_wait_period)), |
57 | body(_body) | |
58 | { | |
59 | thd = std::thread(&RunEvery::run, this); | |
60 | } | |
61 | ||
62 | RunEvery(const RunEvery& other) = delete; | |
63 | RunEvery& operator=(const RunEvery& other) = delete; | |
64 | RunEvery(RunEvery&& other) = delete; | |
65 | #ifdef ADD_MOVE_SEMANTICS | |
66 | RunEvery& operator=(RunEvery&& other); | |
67 | #else | |
68 | RunEvery& operator=(RunEvery&& other) = delete; | |
69 | #endif | |
70 | ||
71 | ~RunEvery(); | |
72 | ||
31f18b77 | 73 | void join(); |
11fdf7f2 TL |
74 | // update wait period in milliseconds |
75 | void try_update(milliseconds _wait_period); | |
31f18b77 | 76 | |
7c673cae FG |
77 | protected: |
78 | ||
79 | void run(); | |
80 | }; | |
81 | } |