summaryrefslogtreecommitdiffstats
path: root/src/common/condition_variable_debug.cc
blob: a2ddd7691a7de5f405da166797717eeb49957cb4 (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
75
76
77
#include "condition_variable_debug.h"
#include "common/mutex_debug.h"

namespace ceph {

condition_variable_debug::condition_variable_debug()
  : waiter_mutex{nullptr}
{
  int r = pthread_cond_init(&cond, nullptr);
  if (r) {
    throw std::system_error(r, std::generic_category());
  }
}

condition_variable_debug::~condition_variable_debug()
{
  pthread_cond_destroy(&cond);
}

void condition_variable_debug::wait(std::unique_lock<mutex_debug>& lock)
{
  // make sure this cond is used with one mutex only
  ceph_assert(waiter_mutex == nullptr ||
         waiter_mutex == lock.mutex());
  waiter_mutex = lock.mutex();
  ceph_assert(waiter_mutex->is_locked());
  waiter_mutex->_pre_unlock();
  if (int r = pthread_cond_wait(&cond, waiter_mutex->native_handle());
      r != 0) {
    throw std::system_error(r, std::generic_category());
  }
  waiter_mutex->_post_lock();
}

void condition_variable_debug::notify_one()
{
  // make sure signaler is holding the waiter's lock.
  ceph_assert(waiter_mutex == nullptr ||
         waiter_mutex->is_locked());
  if (int r = pthread_cond_signal(&cond); r != 0) {
    throw std::system_error(r, std::generic_category());
  }
}

void condition_variable_debug::notify_all(bool sloppy)
{
  // make sure signaler is holding the waiter's lock.
  ceph_assert(waiter_mutex == NULL ||
         waiter_mutex->is_locked());
  if (int r = pthread_cond_broadcast(&cond); r != 0 && !sloppy) {
    throw std::system_error(r, std::generic_category());
  }
}

std::cv_status condition_variable_debug::_wait_until(mutex_debug* mutex,
                                                     timespec* ts)
{
  // make sure this cond is used with one mutex only
  ceph_assert(waiter_mutex == nullptr ||
         waiter_mutex == mutex);
  waiter_mutex = mutex;
  ceph_assert(waiter_mutex->is_locked());

  waiter_mutex->_pre_unlock();
  int r = pthread_cond_timedwait(&cond, waiter_mutex->native_handle(), ts);
  waiter_mutex->_post_lock();
  switch (r) {
  case 0:
    return std::cv_status::no_timeout;
  case ETIMEDOUT:
    return std::cv_status::timeout;
  default:
    throw std::system_error(r, std::generic_category());
  }
}

} // namespace ceph