summaryrefslogtreecommitdiffstats
path: root/src/common/condition_variable_debug.h
blob: f094a5384f3f9a0634b57850a4760bf806cd5f54 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab

#pragma once

#include <condition_variable>
#include <ctime>
#include <pthread.h>
#include "common/ceph_time.h"

namespace ceph {

namespace mutex_debug_detail {
  template<bool> class mutex_debug_impl;
}

class condition_variable_debug {
  using mutex_debug = mutex_debug_detail::mutex_debug_impl<false>;

  pthread_cond_t cond;
  mutex_debug* waiter_mutex;

  condition_variable_debug&
  operator=(const condition_variable_debug&) = delete;
  condition_variable_debug(const condition_variable_debug&) = delete;

public:
  condition_variable_debug();
  ~condition_variable_debug();
  void wait(std::unique_lock<mutex_debug>& lock);
  template<class Predicate>
  void wait(std::unique_lock<mutex_debug>& lock, Predicate pred) {
    while (!pred()) {
      wait(lock);
    }
  }
  template<class Clock, class Duration>
  std::cv_status wait_until(
    std::unique_lock<mutex_debug>& lock,
    const std::chrono::time_point<Clock, Duration>& when) {
    timespec ts = Clock::to_timespec(when);
    return _wait_until(lock.mutex(), &ts);
  }
  template<class Rep, class Period>
  std::cv_status wait_for(
    std::unique_lock<mutex_debug>& lock,
    const std::chrono::duration<Rep, Period>& awhile) {
    ceph::real_time when{ceph::real_clock::now()};
    when += awhile;
    timespec ts = ceph::real_clock::to_timespec(when);
    return _wait_until(lock.mutex(), &ts);
  }
  template<class Rep, class Period, class Pred>
  bool wait_for(
    std::unique_lock<mutex_debug>& lock,
    const std::chrono::duration<Rep, Period>& awhile,
    Pred pred) {
    ceph::real_time when{ceph::real_clock::now()};
    when += awhile;
    timespec ts = ceph::real_clock::to_timespec(when);
    while (!pred()) {
      if ( _wait_until(lock.mutex(), &ts) == std::cv_status::timeout) {
        return pred();
      }
    }
    return true;
  }
  void notify_one();
  void notify_all(bool sloppy = false);
private:
  std::cv_status _wait_until(mutex_debug* mutex, timespec* ts);
};

} // namespace ceph