-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmutex.h
144 lines (121 loc) · 2.18 KB
/
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
/*
locker from Intel 2007, update by ChenWenQing 2007
*/
#ifndef _G_MUTEX_H
#define _G_MUTEX_H
#include <pthread.h>
#include <stdexcept>
#include <stdio.h>
class not_copy
{
not_copy( const not_copy& );
void operator=( const not_copy& );
public:
not_copy() {}
};
class Mutex
{
pthread_mutex_t impl;
void handle_error( int error_code, const char* what )
{
char buf[128];
sprintf(buf,"%s: ",what);
char* end = strchr(buf,0);
size_t n = buf+sizeof(buf)-end;
strncpy( end, strerror( error_code ), n );
buf[sizeof(buf)-1] = 0;
throw std::runtime_error(buf);
}
void inside_construct()
{
int error_code = pthread_mutex_init(&impl,NULL);
if( error_code )
handle_error(error_code,"mutex: pthread_mutex_init failed");
}
void inside_destroy()
{
pthread_mutex_destroy(&impl);
}
public:
Mutex()
{
#if _ASSERT
inside_construct();
#else
int error_code = pthread_mutex_init(&impl,NULL);
if( error_code )
handle_error(error_code,"mutex: pthread_mutex_init failed");
#endif
};
~Mutex()
{
#if _ASSERT
inside_destroy();
#else
pthread_mutex_destroy(&impl);
#endif
};
class area_lock;
friend class area_lock;
class area_lock : private not_copy
{
Mutex* _mutex;
void inside_acquire( Mutex& m )
{
pthread_mutex_lock(&m.impl);
_mutex = &m;
}
bool inside_try_acquire( Mutex& m )
{
bool result = pthread_mutex_trylock(&m.impl)==0;
if( result ) _mutex = &m;
return result;
}
void inside_release()
{
pthread_mutex_unlock(&_mutex->impl);
_mutex = NULL;
}
public:
area_lock() : _mutex(NULL) {};
area_lock( Mutex& mutex )
{
acquire( mutex );
}
~area_lock()
{
if( _mutex ) release();
}
void acquire( Mutex& mutex )
{
#if _ASSERT
inside_acquire(mutex);
#else
_mutex = &mutex;
pthread_mutex_lock(&mutex.impl);
#endif
}
bool try_acquire( Mutex& mutex )
{
#if _ASSERT
return inside_try_acquire (mutex);
#else
bool result = pthread_mutex_trylock(&mutex.impl)==0;
if( result )
_mutex = &mutex;
return result;
#endif
}
void release()
{
#if _ASSERT
inside_release ();
#else
pthread_mutex_unlock(&_mutex->impl);
_mutex = NULL;
#endif
}
};
};
#define LOCK Mutex::area_lock
#endif