-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathydx_mutex.h
73 lines (56 loc) · 1.11 KB
/
ydx_mutex.h
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
#ifndef __YDX_MUTEX_H__
#define __YDX_MUTEX_H__
#include <assert.h>
#include <pthread.h>
#include <boost/noncopyable.hpp>
#define MCHECK(ret) ({ __typeof__ (ret) errnum = (ret); \
if (__builtin_expect(errnum != 0, 0)) \
__assert_perror_fail (errnum, __FILE__, __LINE__, __func__);})
namespace ydx
{
class MutexLock
{
public:
MutexLock()
{
MCHECK(pthread_mutex_init(&mutex_, NULL));
}
~MutexLock()
{
MCHECK(pthread_mutex_destroy(&mutex_));
}
void lock()
{
MCHECK(pthread_mutex_lock(&mutex_));
}
void unlock()
{
MCHECK(pthread_mutex_unlock(&mutex_));
}
pthread_mutex_t* getPthreadMutex() /* non-const */
{
return &mutex_;
}
pthread_mutex_t mutex_;
};
class MutexLockGuard : boost::noncopyable
{
public:
explicit MutexLockGuard(MutexLock& mutex)
: mutex_(mutex)
{
mutex_.lock();
}
~MutexLockGuard()
{
mutex_.unlock();
}
private:
MutexLock& mutex_;
};
// Prevent misuse like:
// MutexLockGuard(mutex_);
// A tempory object doesn't hold the lock for long!
#define MutexLockGuard(x) error "Missing guard object name"
}
#endif