-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlockhandler.cpp
More file actions
47 lines (37 loc) · 1.29 KB
/
lockhandler.cpp
File metadata and controls
47 lines (37 loc) · 1.29 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
#include <algorithm>
#include <iostream>
#include <stdexcept>
#include "lockhandler.hpp"
#include "locknames.hpp"
#include <vector>
#include <pthread.h>
LockHandler::LockHandler(int numLocksIn) {
if(numLocksIn <= 0) {
throw std::invalid_argument("The number of locks this lockhandler is responsible for must be non-negative");
}
for(unsigned int i = 0; i < numLocksIn; ++i) {
this->mutexes.push_back(pthread_mutex_t());
pthread_mutex_init(&this->mutexes.back(), NULL);
}
}
std::vector<pthread_mutex_t>&
LockHandler::getLocks() {
return this->mutexes;
}
void
LockHandler::acquireLocks(std::initializer_list<LockName> lockNames) {
std::vector<LockName> locksToAcquire(lockNames.begin(), lockNames.end());
std::sort(locksToAcquire.begin(), locksToAcquire.end());
for(LockName lockName : locksToAcquire) {
pthread_mutex_lock(&this->mutexes[lockName]);
}
}
void
LockHandler::releaseLocks(std::initializer_list<LockName> lockNames) {
std::vector<LockName> locksToRelease(lockNames.begin(), lockNames.end());
std::sort(locksToRelease.begin(), locksToRelease.end());
std::reverse(locksToRelease.begin(), locksToRelease.end());
for(LockName lockName : locksToRelease) {
pthread_mutex_unlock(&this->mutexes[lockName]);
}
}