]> git.proxmox.com Git - ceph.git/blob - ceph/src/dmclock/support/src/run_every.h
update sources to v12.1.0
[ceph.git] / ceph / src / dmclock / support / src / run_every.h
1 // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
2 // vim: ts=8 sw=2 smarttab
3 /*
4 * Copyright (C) 2017 Red Hat Inc.
5 */
6
7
8 #pragma once
9
10 #include <chrono>
11 #include <mutex>
12 #include <condition_variable>
13 #include <thread>
14 #include <functional>
15
16 namespace crimson {
17 using std::chrono::duration_cast;
18 using std::chrono::milliseconds;
19
20 // runs a given simple function object waiting wait_period
21 // milliseconds between; the destructor stops the other thread
22 // immediately
23 class RunEvery {
24 using Lock = std::unique_lock<std::mutex>;
25 using Guard = std::lock_guard<std::mutex>;
26 using TimePoint = std::chrono::steady_clock::time_point;
27
28 bool finishing = false;
29 std::chrono::milliseconds wait_period;
30 std::function<void()> body;
31 std::mutex mtx;
32 std::condition_variable cv;
33
34 // put threads last so all other variables are initialized first
35
36 std::thread thd;
37
38 public:
39
40 #ifdef ADD_MOVE_SEMANTICS
41 RunEvery();
42 #endif
43
44 template<typename D>
45 RunEvery(D _wait_period,
46 std::function<void()> _body) :
47 wait_period(duration_cast<milliseconds>(_wait_period)),
48 body(_body)
49 {
50 thd = std::thread(&RunEvery::run, this);
51 }
52
53 RunEvery(const RunEvery& other) = delete;
54 RunEvery& operator=(const RunEvery& other) = delete;
55 RunEvery(RunEvery&& other) = delete;
56 #ifdef ADD_MOVE_SEMANTICS
57 RunEvery& operator=(RunEvery&& other);
58 #else
59 RunEvery& operator=(RunEvery&& other) = delete;
60 #endif
61
62 ~RunEvery();
63
64 void join();
65
66 protected:
67
68 void run();
69 };
70 }