-
Notifications
You must be signed in to change notification settings - Fork 29
/
locks.hh
87 lines (71 loc) · 1.55 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
78
79
80
81
82
83
84
85
86
87
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
#ifndef LOCKS_H
#define LOCKS_H 1
#include <stdexcept>
#include <iostream>
#include <sstream>
#include "common.hh"
#include "mutex.hh"
#include "syncobject.hh"
class LockHolder {
public:
/**
* Acquire the lock in the given mutex.
*/
LockHolder(Mutex &m) : mutex(m), locked(false) {
lock();
}
/**
* Release the lock.
*/
~LockHolder() {
unlock();
}
void lock() {
mutex.acquire();
locked = true;
}
void unlock() {
if (locked) {
locked = false;
mutex.release();
}
}
private:
Mutex &mutex;
bool locked;
DISALLOW_COPY_AND_ASSIGN(LockHolder);
};
class MultiLockHolder {
public:
MultiLockHolder(Mutex *m, size_t n) : mutexes(m),
locked(NULL),
n_locks(n) {
locked = new bool[n];
lock();
}
~MultiLockHolder() {
unlock();
delete[] locked;
}
void lock() {
for (size_t i = 0; i < n_locks; i++) {
mutexes[i].acquire();
locked[i] = true;
}
}
void unlock() {
for (size_t i = 0; i < n_locks; i++) {
if (locked[i]) {
locked[i] = false;
mutexes[i].release();
}
}
}
private:
Mutex *mutexes;
bool *locked;
size_t n_locks;
DISALLOW_COPY_AND_ASSIGN(MultiLockHolder);
};
#endif /* LOCKS_H */