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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
|
/*
* Copyright (c) 2005, Eric Crahen
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is furnished
* to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
#ifndef __ZTSEMAPHOREIMPL_H__
#define __ZTSEMAPHOREIMPL_H__
#include "zthread/Guard.h"
#include "Debug.h"
#include "FastLock.h"
#include "Scheduling.h"
#include <assert.h>
namespace ZThread {
class Monitor;
/**
* @class SemaphoreImpl
* @author Eric Crahen <http://www.code-foo.com>
* @date <2003-07-16T20:03:20-0400>
* @version 2.2.11
*
* The SemaphoreImpl template allows how waiter lists are sorted
* to be parameteized
*/
template <typename List>
class SemaphoreImpl {
//! List of waiting events
List _waiters;
//! Serialize access to this object
FastLock _lock;
//! Current count
volatile int _count;
//! Maximum count if any
volatile int _maxCount;
//! Flag for bounded or unbounded count
volatile bool _checked;
//! Entry count
volatile int _entryCount;
public:
/**
* Create a new SemaphoreImpl. Initialzes one pthreads mutex for
* internal use.
*
* @exception Initialization_Exception thrown if resources could not be
* properly allocated
*/
SemaphoreImpl(int count, unsigned int maxCount, bool checked)
: _count(count), _maxCount(maxCount), _checked(checked), _entryCount(0) { }
~SemaphoreImpl();
void acquire();
void release();
bool tryAcquire(unsigned long timeout);
int count();
};
/**
* Destroy this SemaphoreImpl and release its resources.
*/
template <typename List>
SemaphoreImpl<List>::~SemaphoreImpl() {
#ifndef NDEBUG
if(!_waiters.empty()) {
ZTDEBUG("** You are destroying a semaphore which is blocking %d threads. **\n", _waiters.size());
assert(0); // Destroyed semaphore while in use
}
#endif
}
/**
* Get the count for the Semaphore
*
* @return int
*/
template <typename List>
int SemaphoreImpl<List>::count() {
Guard<FastLock> g(_lock);
return _count;
}
/**
* Decrement the count, blocking when that count becomes 0 or less.
*
* @exception Interrupted_Exception thrown when the caller status is interrupted
* @exception Synchronization_Exception thrown if there is some other error.
*/
template <typename List>
void SemaphoreImpl<List>::acquire() {
// Get the monitor for the current thread
ThreadImpl* self = ThreadImpl::current();
Monitor& m = self->getMonitor();
Monitor::STATE state;
Guard<FastLock> g1(_lock);
// Update the count without waiting if possible.
if(_count > 0 && _entryCount == 0)
_count--;
// Otherwise, wait() for the lock by placing the waiter in the list
else {
++_entryCount;
_waiters.insert(self);
m.acquire();
{
Guard<FastLock, UnlockedScope> g2(g1);
state = m.wait();
}
m.release();
// Remove from waiter list, regarless of weather release() is called or
// not. The monitor is sticky, so its possible a state 'stuck' from a
// previous operation and will leave the wait() w/o release() having
// been called.
typename List::iterator i = std::find(_waiters.begin(), _waiters.end(), self);
if(i != _waiters.end())
_waiters.erase(i);
--_entryCount;
switch(state) {
// If awoke due to a notify(), update the count
case Monitor::SIGNALED:
_count--;
break;
case Monitor::INTERRUPTED:
throw Interrupted_Exception();
default:
throw Synchronization_Exception();
}
}
}
/**
* Decrement the count, blocking when it that count is 0 or less. If the timeout
* expires before the count is raise above 0, the thread will stop blocking
* and return.
*
* @exception Interrupted_Exception thrown when the caller status is interrupted
* @exception Synchronization_Exception thrown if there is some other error.
*/
template <typename List>
bool SemaphoreImpl<List>::tryAcquire(unsigned long timeout) {
// Get the monitor for the current thread
ThreadImpl* self = ThreadImpl::current();
Monitor& m = self->getMonitor();
Guard<FastLock> g1(_lock);
// Update the count without waiting if possible.
if(_count > 0 && _entryCount == 0)
_count--;
// Otherwise, wait() for the lock by placing the waiter in the list
else {
++_entryCount;
_waiters.push_back(self);
Monitor::STATE state = Monitor::TIMEDOUT;
// Don't bother waiting if the timeout is 0
if(timeout) {
m.acquire();
{
Guard<FastLock, UnlockedScope> g2(g1);
state = m.wait(timeout);
}
m.release();
}
// Remove from waiter list, regarless of weather release() is called or
// not. The monitor is sticky, so its possible a state 'stuck' from a
// previous operation and will leave the wait() w/o release() having
// been called.
typename List::iterator i = std::find(_waiters.begin(), _waiters.end(), self);
if(i != _waiters.end())
_waiters.erase(i);
--_entryCount;
switch(state) {
// If awoke due to a notify(), update the count
case Monitor::SIGNALED:
_count--;
break;
case Monitor::INTERRUPTED:
throw Interrupted_Exception();
case Monitor::TIMEDOUT:
return false;
default:
throw Synchronization_Exception();
}
}
return true;
}
/**
* Increment the count and release a waiter if there are any. If the semaphore
* is checked, then an exception will be raised if the maximum count is about to
* be exceeded.
*
* @exception InvalidOp_Exception thrown if the maximum count is exceeded while
* the checked flag is set.
*/
template <typename List>
void SemaphoreImpl<List>::release() {
Guard<FastLock> g1(_lock);
// Make sure the operation is valid
if(_checked && _count == _maxCount)
throw InvalidOp_Exception();
// Increment the count
_count++;
// Try to find a waiter with a backoff & retry scheme
for(;;) {
// Go through the list, attempt to notify() a waiter.
for(typename List::iterator i = _waiters.begin(); i != _waiters.end();) {
// Try the monitor lock, if it cant be locked skip to the next waiter
ThreadImpl* impl = *i;
Monitor& m = impl->getMonitor();
if(m.tryAcquire()) {
// Notify the monitor & remove from the waiter list so time isn't
// wasted checking it again.
i = _waiters.erase(i);
// If notify() is not sucessful, it is because the wait() has already
// been ended (killed/interrupted/notify'd)
bool woke = m.notify();
m.release();
// Once notify() succeeds, return
if(woke)
return;
} else ++i;
}
if(_waiters.empty())
return;
{ // Backoff and try again
Guard<FastLock, UnlockedScope> g2(g1);
ThreadImpl::yield();
}
}
}
class FifoSemaphoreImpl : public SemaphoreImpl<fifo_list> {
public:
FifoSemaphoreImpl(int count, unsigned int maxCount, bool checked)
/* throw(Synchronization_Exception) */
: SemaphoreImpl<fifo_list>(count, maxCount, checked) { }
};
} // namespace ZThread
#endif // __ZTSEMAPHOREIMPL_H__
|