-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmutex.cpp
95 lines (80 loc) · 1.35 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
86
87
88
89
90
91
92
93
94
95
#ifdef PTHREAD
#include"mutex.h"
namespace Mutex{
MutexLock::MutexLock(){
#ifdef PTHREAD
pthread_mutex_init(&mutex_, NULL);
#endif
}
MutexLock::~MutexLock(){
#ifdef PTHREAD
pthread_mutex_destroy(&mutex_);
#endif
}
void MutexLock::Lock(){
#ifdef PTHREAD
pthread_mutex_lock(&mutex_);
#else
mutex_.lock();
#endif
}
void MutexLock::UnLock(){
#ifdef PTHREAD
pthread_mutex_unlock(&mutex_);
#else
mutex_.unlock();
#endif
}
#ifdef PTHREAD
pthread_mutex_t* MutexLock::GetPthreadMutex(){
return &mutex_;
}
#else
std::mutex* MutexLock::GetPthreadMutex(){
return &mutex_;
}
#endif
//Condition
Condition::Condition(MutexLock& lock):
mutex_lock_(lock)
{
#ifdef PTHREAD
pthread_cond_init(&pcond_, NULL);
#endif
}
Condition::~Condition(){
#ifdef PTHREAD
pthread_cond_destroy(&pcond_);
#endif
}
void Condition::Wait(){
#ifdef PTHREAD
pthread_cond_wait(&pcond_, mutex_lock_.GetPthreadMutex());
#endif
}
int Condition::WaitTimeOut(int timeout){
#ifdef PTHREAD
struct timespec timer;
timer.tv_sec = time(0) + timeout;
timer.tv_nsec = 0;
return pthread_cond_timedwait(&pcond_, mutex_lock_.GetPthreadMutex(), &timer);
#else
return 0;
#endif
}
void Condition::Notify(){
#ifdef PTHREAD
pthread_cond_signal(&pcond_);
#else
pcond_.notify_one();
#endif
}
void Condition::NotifyAll(){
#ifdef PTHREAD
pthread_cond_broadcast(&pcond_);
#else
pcond_.notify_all();
#endif
}
};
#endif