forked from couchbase/ep-engine
/
syncobject.hh
79 lines (66 loc) · 1.89 KB
/
syncobject.hh
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
78
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
#ifndef SYNCOBJECT_HH
#define SYNCOBJECT_HH 1
#include <stdexcept>
#include <iostream>
#include <sstream>
#include <pthread.h>
#include <sys/time.h>
#include "common.hh"
/**
* Abstraction built on top of pthread mutexes
*/
class SyncObject : public Mutex {
public:
SyncObject() : Mutex() {
#ifdef VALGRIND
// valgrind complains about an uninitialzed memory read
// if we just initialize the cond with pthread_cond_init.
memset(&cond, 0, sizeof(cond));
#endif
if (pthread_cond_init(&cond, NULL) != 0) {
throw std::runtime_error("MUTEX ERROR: Failed to initialize cond.");
}
}
~SyncObject() {
if (pthread_cond_destroy(&cond) != 0) {
throw std::runtime_error("MUTEX ERROR: Failed to destroy cond.");
}
}
void wait() {
if (pthread_cond_wait(&cond, &mutex) != 0) {
throw std::runtime_error("Failed to wait for condition.");
}
setHolder(true);
}
bool wait(const struct timeval &tv) {
struct timespec ts;
ts.tv_sec = tv.tv_sec + 0;
ts.tv_nsec = tv.tv_usec * 1000;
switch (pthread_cond_timedwait(&cond, &mutex, &ts)) {
case 0:
setHolder(true);
return true;
case ETIMEDOUT:
setHolder(true);
return false;
default:
throw std::runtime_error("Failed timed_wait for condition.");
}
}
bool wait(const double secs) {
struct timeval tv;
gettimeofday(&tv, NULL);
advance_tv(tv, secs);
return wait(tv);
}
void notify() {
if(pthread_cond_broadcast(&cond) != 0) {
throw std::runtime_error("Failed to broadcast change.");
}
}
private:
pthread_cond_t cond;
DISALLOW_COPY_AND_ASSIGN(SyncObject);
};
#endif