blob: 6a9188558747897bec62d17d42a4deb58f2c9095 (
plain)
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
|
#include "Mutex.h"
#include <cassert>
#include <pthread.h>
#ifndef CRU_WINDOWS
#include <errno.h>
#endif
namespace cru {
Mutex::Mutex() {
#ifdef CRU_WINDOWS
#else
mutex_ = std::make_unique<pthread_mutex_t>();
auto c = pthread_mutex_init(mutex_.get(), nullptr);
assert(c == 0);
#endif
}
Mutex::Mutex(Mutex &&other)
#ifdef CRU_WINDOWS
#else
: mutex_(std::move(other.mutex_))
#endif
{
}
Mutex &Mutex::operator=(Mutex &&other) {
if (this != &other) {
Destroy();
mutex_ = std::move(other.mutex_);
}
return *this;
}
Mutex::~Mutex() { Destroy(); }
void Mutex::Lock() {
#ifdef CRU_WINDOWS
#else
assert(mutex_);
auto c = pthread_mutex_lock(mutex_.get());
assert(c == 0);
#endif
}
bool Mutex::TryLock() {
#ifdef CRU_WINDOWS
#else
assert(mutex_);
auto c = pthread_mutex_trylock(mutex_.get());
assert(c == 0 || c == EBUSY);
return c == 0 ? true : false;
#endif
}
void Mutex::Unlock() {
#ifdef CRU_WINDOWS
#else
assert(mutex_);
auto c = pthread_mutex_unlock(mutex_.get());
assert(c == 0);
#endif
}
void Mutex::Destroy() {
#ifdef CRU_WINDOWS
#else
if (mutex_ != nullptr) {
auto c = pthread_mutex_destroy(mutex_.get());
assert(c);
mutex_ = nullptr;
}
#endif
}
} // namespace cru
|