]> git.proxmox.com Git - ceph.git/blob - ceph/src/common/CondVar.h
update source to 12.2.11
[ceph.git] / ceph / src / common / CondVar.h
1 #ifndef CEPH_COND_VAR_H
2 #define CEPH_COND_VAR_H
3
4 #include "include/utime.h"
5
6 #include "Clock.h"
7 #include "Mutex.h"
8 #include "pthread.h"
9
10 class Cond {
11 // my bits
12 pthread_cond_t _c;
13
14 Mutex *waiter_mutex;
15
16 // don't allow copying.
17 void operator=(Cond &C);
18 Cond(const Cond &C);
19
20 public:
21 Cond() : waiter_mutex(NULL) {
22 int r = pthread_cond_init(&_c,NULL);
23 assert(r == 0);
24 }
25 virtual ~Cond() {
26 pthread_cond_destroy(&_c);
27 }
28
29 int Wait(Mutex &mutex) {
30 // make sure this cond is used with one mutex only
31 assert(waiter_mutex == NULL || waiter_mutex == &mutex);
32 waiter_mutex = &mutex;
33
34 assert(mutex.is_locked());
35
36 mutex._pre_unlock();
37 int r = pthread_cond_wait(&_c, &mutex._m);
38 mutex._post_lock();
39 return r;
40 }
41
42 int WaitUntil(Mutex &mutex, utime_t when) {
43 // make sure this cond is used with one mutex only
44 assert(waiter_mutex == NULL || waiter_mutex == &mutex);
45 waiter_mutex = &mutex;
46
47 assert(mutex.is_locked());
48
49 struct timespec ts;
50 when.to_timespec(&ts);
51
52 mutex._pre_unlock();
53 int r = pthread_cond_timedwait(&_c, &mutex._m, &ts);
54 mutex._post_lock();
55
56 return r;
57 }
58
59 int WaitInterval(Mutex &mutex, utime_t interval) {
60 utime_t when = ceph_clock_now();
61 when += interval;
62 return WaitUntil(mutex, when);
63 }
64
65 template<typename Duration>
66 int WaitInterval(Mutex &mutex, Duration interval) {
67 ceph::real_time when(ceph::real_clock::now());
68 when += interval;
69
70 struct timespec ts = ceph::real_clock::to_timespec(when);
71
72 mutex._pre_unlock();
73 int r = pthread_cond_timedwait(&_c, &mutex._m, &ts);
74 mutex._post_lock();
75
76 return r;
77 }
78
79 int SloppySignal() {
80 int r = pthread_cond_broadcast(&_c);
81 return r;
82 }
83 int Signal() {
84 // make sure signaler is holding the waiter's lock.
85 assert(waiter_mutex == NULL ||
86 waiter_mutex->is_locked());
87
88 int r = pthread_cond_broadcast(&_c);
89 return r;
90 }
91 int SignalOne() {
92 // make sure signaler is holding the waiter's lock.
93 assert(waiter_mutex == NULL ||
94 waiter_mutex->is_locked());
95
96 int r = pthread_cond_signal(&_c);
97 return r;
98 }
99 int SignalAll() {
100 // make sure signaler is holding the waiter's lock.
101 assert(waiter_mutex == NULL ||
102 waiter_mutex->is_locked());
103
104 int r = pthread_cond_broadcast(&_c);
105 return r;
106 }
107 };
108
109 #endif // CEPH_COND_VAR_H