-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlockableVector.hpp
More file actions
103 lines (75 loc) · 2.11 KB
/
Copy pathlockableVector.hpp
File metadata and controls
103 lines (75 loc) · 2.11 KB
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/**
* \file lockableVector.hpp
* \brief Definition and implementation of LockableVector class
* \author Luca Di Mauro
*/
#ifndef LOCAKBLE_VECTOR_HPP
#define LOCAKBLE_VECTOR_HPP
#include <vector>
#include <mutex>
#include <condition_variable>
// Forward class declaration
template<typename T>
class LockableVector;
/* Class which represent an already locked vector owned by related 'LockableVector' class instance.
* In the destructor, original vector is released.
*/
template<typename T>
class LockedVector {
private :
LockableVector<T>& parent;
public :
std::vector<T>& data;
LockedVector (std::vector<T>& origVect, LockableVector<T> *locker) : parent (*locker), data (origVect) {}
~LockedVector () {
parent.releaseVector ();
}
};
/* Class which stores a vector of type T and allows to get it either in a shared environment using synchronization mechanisms,
* or obtaining it without synchronization.
*/
template <typename T>
class LockableVector {
private:
friend class LockedVector<T>;
std::vector<T> dataVector;
std::mutex vectorMutex;
std::condition_variable vectorCV;
void releaseVector () {
vectorMutex.unlock ();
}
public:
LockableVector (std::vector<T> &externalVector) : dataVector(externalVector) {
}
LockableVector (LockableVector &&lv) {
dataVector = std::vector<T> (lv.dataVector.size());
}
LockableVector () {
// Do nothing
}
~LockableVector () {
// Do nothing
}
bool isEmpty () {
std::unique_lock<std::mutex> lock (vectorMutex);
return dataVector.empty ();
}
std::vector<T>& getVector () {
return dataVector;
}
void swap (std::vector<T> &targetVector) {
std::unique_lock<std::mutex> lock (vectorMutex);
std::swap (dataVector, targetVector);
}
std::shared_ptr<LockedVector<T>> lockAndGet () {
vectorMutex.lock ();
return std::shared_ptr<LockedVector<T>> (new LockedVector<T> (dataVector, this));
}
std::shared_ptr<LockedVector<T>> tryLockAndGet () {
if (vectorMutex.try_lock ()) {
return std::shared_ptr<LockedVector<T>> (new LockedVector<T> (dataVector, this));
}
throw std::logic_error ("No lock acquired");
}
};
#endif // LOCAKBLE_VECTOR_HPP