Fix some bugs when testing opensds ansible
[stor4nfv.git] / src / ceph / src / dmclock / support / src / run_every.cc
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 #include "run_every.h"
9
10
11 // can define ADD_MOVE_SEMANTICS, although not fully debugged and tested
12
13
14 namespace chrono = std::chrono;
15
16
17 #ifdef ADD_MOVE_SEMANTICS
18 crimson::RunEvery::RunEvery()
19 {
20   // empty
21 }
22
23
24 crimson::RunEvery& crimson::RunEvery::operator=(crimson::RunEvery&& other)
25 {
26   // finish run every thread
27   {
28     Guard g(mtx);
29     finishing = true;
30     cv.notify_one();
31   }
32   if (thd.joinable()) {
33     thd.join();
34   }
35
36   // transfer info over from previous thread
37   finishing.store(other.finishing);
38   wait_period = other.wait_period;
39   body = other.body;
40
41   // finish other thread
42   other.finishing.store(true);
43   other.cv.notify_one();
44
45   // start this thread
46   thd = std::thread(&RunEvery::run, this);
47
48   return *this;
49 }
50 #endif
51
52
53 crimson::RunEvery::~RunEvery() {
54   join();
55 }
56
57
58 void crimson::RunEvery::join() {
59   {
60     Guard l(mtx);
61     if (finishing) return;
62     finishing = true;
63     cv.notify_all();
64   }
65   thd.join();
66 }
67
68
69 void crimson::RunEvery::run() {
70   Lock l(mtx);
71   while(!finishing) {
72     TimePoint until = chrono::steady_clock::now() + wait_period;
73     while (!finishing && chrono::steady_clock::now() < until) {
74       cv.wait_until(l, until);
75     }
76     if (!finishing) {
77       body();
78     }
79   }
80 }