-
Notifications
You must be signed in to change notification settings - Fork 5
/
locks.hh
77 lines (68 loc) · 2 KB
/
locks.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
#ifndef LOCKS_HH
#define LOCKS_HH 1
#include <cstring>
#include <pthread.h>
namespace labrea {
class LockHolder {
public:
LockHolder(pthread_mutex_t *m) : mutex(m), locked(false) {
lock();
}
~LockHolder() {
unlock();
}
void lock() {
int e(0);
pthread_mutexattr_t attr;
if (pthread_mutexattr_init(&attr) != 0 ||
(e = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK)) != 0) {
std::string message = "MUTEX ERROR: Failed to initialize mutex: ";
message.append(std::strerror(e));
throw std::runtime_error(message);
}
if ((e = pthread_mutex_lock(mutex)) != 0) {
std::string message = "MUTEX ERROR: Failed to acquire lock: ";
message.append(std::strerror(e));
throw std::runtime_error(message);
}
locked = true;
}
void unlock() {
if (locked) {
locked = false;
int e;
if ((e = pthread_mutex_unlock(mutex)) != 0) {
std::string message = "MUTEX_ERROR: Failed to release lock: ";
message.append(std::strerror(e));
throw std::runtime_error(message);
}
}
}
private:
pthread_mutex_t *mutex;
bool locked;
};
// Like a LockHolder, but temporarily releases the lock.
class AntiLockHolder {
public:
AntiLockHolder(pthread_mutex_t *m) : mutex(m) {
int e;
if ((e = pthread_mutex_unlock(mutex)) != 0) {
std::string message = "MUTEX_ERROR: Failed to release lock: ";
message.append(std::strerror(e));
throw std::runtime_error(message);
}
}
~AntiLockHolder() {
int e;
if ((e = pthread_mutex_lock(mutex)) != 0) {
std::string message = "MUTEX ERROR: Failed to acquire lock: ";
message.append(std::strerror(e));
throw std::runtime_error(message);
}
}
private:
pthread_mutex_t *mutex;
};
}
#endif /* LOCKS_HH */