-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmutex.cpp
85 lines (70 loc) · 2.06 KB
/
mutex.cpp
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
/*
* Copyright 2011 Andrew H. Armenia.
*
* This file is part of openreplay.
*
* openreplay is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* openreplay is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with openreplay. If not, see <http://www.gnu.org/licenses/>.
*/
#include "mutex.h"
#include <pthread.h>
#include <stdexcept>
#include "posix_error.h"
#include <sys/time.h>
#include <stdio.h>
#include <errno.h>
static void throw_on_error(int ret, const char *msg) {
if (ret != 0) {
errno = ret;
throw POSIXError(msg);
}
}
Mutex::Mutex( ) {
pthread_mutexattr_t attr;
if (pthread_mutexattr_init(&attr) != 0) {
throw std::runtime_error("Failed to initialize mutex attribute");
}
if (pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE) != 0) {
throw std::runtime_error("Failed to set mutex as recursive");
}
if (pthread_mutex_init(&mut, &attr) != 0) {
throw std::runtime_error("Failed to initialize mutex");
}
pthread_mutexattr_destroy(&attr);
}
Mutex::~Mutex( ) {
if (pthread_mutex_destroy(&mut) != 0) {
throw std::runtime_error("Failed to destroy mutex");
}
}
void Mutex::lock( ) {
throw_on_error(pthread_mutex_lock(&mut), "Failed to lock mutex");
}
void Mutex::unlock( ) {
if (pthread_mutex_unlock(&mut) != 0) {
throw std::runtime_error("Failed to unlock mutex");
}
}
MutexLock::MutexLock(Mutex &mut) : _mut(&mut) {
_mut->lock( );
locked = true;
}
void MutexLock::force_unlock( ) {
_mut->unlock( );
locked = false;
}
MutexLock::~MutexLock( ) {
if (locked) {
_mut->unlock( );
}
}