-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathmutex.cpp
More file actions
54 lines (44 loc) · 1.22 KB
/
Copy pathmutex.cpp
File metadata and controls
54 lines (44 loc) · 1.22 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
//
// mutex.cpp
// cpp-pthread
//
// Created by herbert koelman on 18/03/2016.
//
//
#include "pthread/mutex.hpp"
namespace pthread {
mutex::mutex() {
auto rc = pthread_mutex_init(&_mutex, NULL);
if (rc != 0) {
throw mutex_exception("In constructor of mutex pthread_mutex_init(&mutex, NULL) failed. ", rc);
}
}
mutex::~mutex() {
pthread_mutex_destroy(&_mutex);
}
void mutex::lock() {
int rc = -1;
rc = pthread_mutex_lock(&_mutex);
if (rc != 0) {
throw mutex_exception("pthread_mutex_lock failed.", rc);
}
}
bool mutex::try_lock() {
bool status = false;
auto rc = pthread_mutex_trylock(&_mutex);
if (rc == 0) {
status = true; // mutex is locked now
}else if ( rc == EBUSY){
status = false ; // mutex is held by some other thread
} else {
throw mutex_exception("pthread_mutex_trylock failed, already locked.", rc);
}
return status ;
}
void mutex::unlock() {
auto rc = pthread_mutex_unlock(&_mutex);
if (rc != 0) {
throw mutex_exception("pthread_mutex_unlock failed.", rc);
}
}
}