]>
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 | ||
7c673cae FG |
16 | #include "run_every.h" |
17 | ||
18 | ||
19 | // can define ADD_MOVE_SEMANTICS, although not fully debugged and tested | |
20 | ||
21 | ||
22 | namespace chrono = std::chrono; | |
23 | ||
24 | ||
25 | #ifdef ADD_MOVE_SEMANTICS | |
26 | crimson::RunEvery::RunEvery() | |
27 | { | |
28 | // empty | |
29 | } | |
30 | ||
31 | ||
32 | crimson::RunEvery& crimson::RunEvery::operator=(crimson::RunEvery&& other) | |
33 | { | |
34 | // finish run every thread | |
35 | { | |
36 | Guard g(mtx); | |
37 | finishing = true; | |
38 | cv.notify_one(); | |
39 | } | |
40 | if (thd.joinable()) { | |
41 | thd.join(); | |
42 | } | |
43 | ||
44 | // transfer info over from previous thread | |
45 | finishing.store(other.finishing); | |
46 | wait_period = other.wait_period; | |
47 | body = other.body; | |
48 | ||
49 | // finish other thread | |
50 | other.finishing.store(true); | |
51 | other.cv.notify_one(); | |
52 | ||
53 | // start this thread | |
54 | thd = std::thread(&RunEvery::run, this); | |
55 | ||
56 | return *this; | |
57 | } | |
58 | #endif | |
59 | ||
60 | ||
61 | crimson::RunEvery::~RunEvery() { | |
31f18b77 FG |
62 | join(); |
63 | } | |
64 | ||
65 | ||
66 | void crimson::RunEvery::join() { | |
67 | { | |
68 | Guard l(mtx); | |
69 | if (finishing) return; | |
70 | finishing = true; | |
71 | cv.notify_all(); | |
72 | } | |
7c673cae FG |
73 | thd.join(); |
74 | } | |
75 | ||
11fdf7f2 TL |
76 | // mtx must be held by caller |
77 | void crimson::RunEvery::try_update(milliseconds _wait_period) { | |
78 | if (_wait_period != wait_period) { | |
79 | wait_period = _wait_period; | |
80 | } | |
81 | } | |
7c673cae FG |
82 | |
83 | void crimson::RunEvery::run() { | |
84 | Lock l(mtx); | |
85 | while(!finishing) { | |
86 | TimePoint until = chrono::steady_clock::now() + wait_period; | |
87 | while (!finishing && chrono::steady_clock::now() < until) { | |
88 | cv.wait_until(l, until); | |
89 | } | |
90 | if (!finishing) { | |
91 | body(); | |
92 | } | |
93 | } | |
94 | } |