-
Notifications
You must be signed in to change notification settings - Fork 4
/
GSIOThreadPool.m
426 lines (365 loc) · 9.06 KB
/
GSIOThreadPool.m
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
/**
Copyright (C) 2010 Free Software Foundation, Inc.
Written by: Richard Frith-Macdonald <rfm@gnu.org>
Date: September 2010
This file is part of the Performance Library.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA.
*/
#import <Foundation/NSArray.h>
#import <Foundation/NSDate.h>
#import <Foundation/NSLock.h>
#import <Foundation/NSRunLoop.h>
#import <Foundation/NSThread.h>
#import <Foundation/NSTimer.h>
#import <Foundation/NSException.h>
#import <Foundation/NSUserDefaults.h>
#import <Foundation/NSAutoreleasePool.h>
#import "GSIOThreadPool.h"
#if !defined (GNUSTEP)
#import "GNUstep.h"
#endif
/* Protect changes to a thread's counter
*/
static NSRecursiveLock *classLock = nil;
@interface GSIOThread (Private)
- (NSUInteger) _count;
- (void) _finish: (NSTimer*)t;
- (void) _setCount: (NSUInteger)c;
@end
@implementation GSIOThread (Private)
+ (void) initialize
{
if (nil == classLock)
{
classLock = [NSRecursiveLock new];
}
}
- (NSUInteger) _count
{
return _count;
}
/* Force termination of this thread.
*/
- (void) _finish: (NSTimer*)t
{
_timer = nil;
[self shutdown];
[NSThread exit];
}
- (void) _setCount: (NSUInteger)c
{
if (NSNotFound != _count)
{
_count = c;
}
}
@end
@implementation GSIOThread
/* Run the thread's main runloop until terminated.
*/
- (void) main
{
NSAutoreleasePool *pool = [NSAutoreleasePool new];
NSDate *when = [NSDate distantFuture];
NSTimeInterval delay = [when timeIntervalSinceNow];
[self startup];
_timer = [NSTimer scheduledTimerWithTimeInterval: delay
target: self
selector: @selector(_finish:)
userInfo: nil
repeats: NO];
[[NSRunLoop currentRunLoop] run];
[pool release];
}
- (void) shutdown
{
return;
}
- (void) startup
{
return;
}
/* End execution of the thread by the specified date.
*/
- (void) terminate: (NSDate*)when
{
if (YES == [self isFinished])
{
return;
}
if (NO == [when isKindOfClass: [NSDate class]])
{
when = [NSDate date];
}
[self retain];
if ([NSThread currentThread] == self)
{
NSTimeInterval delay = [when timeIntervalSinceNow];
[_timer invalidate];
[classLock lock];
if (0 == _count || delay <= 0.0)
{
_count = NSNotFound; // Mark as terminating
_timer = nil;
delay = 0.0;
}
[classLock unlock];
if (delay > 0.0)
{
_timer = [NSTimer scheduledTimerWithTimeInterval: delay
target: self
selector: @selector(_finish:)
userInfo: nil
repeats: NO];
}
else
{
[self _finish: nil];
}
}
else if ([self isExecuting])
{
NSRunLoop *loop;
/* We need to execute -terminate: in the thread itself,
* and wait until either the thread actually finishes or
* until our time limit expires, whichever comes first.
*/
[self performSelector: _cmd
onThread: self
withObject: when
waitUntilDone: NO];
loop = [NSRunLoop currentRunLoop];
while ([self isExecuting] && [when timeIntervalSinceNow] > 0.0)
{
NSDate *d;
d = [[NSDate alloc] initWithTimeIntervalSinceNow: 0.01];
NS_DURING
{
[loop runUntilDate: d];
}
NS_HANDLER
{
NSLog(@"Problem waiting for thread termination: %@",
localException);
}
NS_ENDHANDLER
[d release];
}
}
[self release];
}
@end
@implementation GSIOThreadPool
static GSIOThreadPool *shared = nil;
/* Return the thread with the lowest usage.
* If there are more threads in the array than we want to use,
* those excess threads are excluded from the check so that
* their usage can drop to zero and they can be terminated.
*/
static GSIOThread *
best(NSMutableArray *a, NSUInteger max)
{
NSUInteger c = [a count];
NSUInteger l = NSNotFound;
GSIOThread *t = nil;
if (c > max)
{
c = max;
}
while (c-- > 0)
{
GSIOThread *o = [a objectAtIndex: c];
if ([o isExecuting])
{
NSUInteger i;
if ((i = [o _count]) < l)
{
t = o;
l = i;
}
}
else if ([o isCancelled] || [o isFinished])
{
[a removeObjectAtIndex: c];
}
}
return t;
}
+ (void) initialize
{
if ([GSIOThreadPool class] == self && nil == shared)
{
NSInteger size;
[GSIOThread class];
size = [[NSUserDefaults standardUserDefaults]
integerForKey: @"GSIOThreadPoolSize"];
if (size < 0)
{
size = 0;
}
shared = [self new];
[shared setThreads: size];
}
}
+ (GSIOThreadPool*) sharedPool
{
return shared;
}
- (NSThread*) acquireThread
{
GSIOThread *t;
NSUInteger c;
if (0 == maxThreads)
{
return [NSThread mainThread];
}
[classLock lock];
t = best(threads, maxThreads);
if (nil == t || ((c = [t _count]) > 0 && [threads count] < maxThreads))
{
NSString *n;
t = [threadClass new];
if (nil == (n = poolName))
{
n = @"GSIOThreadPool";
}
n = [NSString stringWithFormat: @"%@-%u", n, ++created];
[t setName: n];
[threads addObject: t];
[t release];
[t start];
c = 0;
}
[t _setCount: c + 1];
[classLock unlock];
return t;
}
- (NSUInteger) countForThread: (NSThread*)aThread
{
NSUInteger count = 0;
[classLock lock];
if ([threads indexOfObjectIdenticalTo: aThread] != NSNotFound)
{
count = [((GSIOThread*)aThread) _count];
}
[classLock unlock];
return count;
}
- (void) dealloc
{
#if defined(GNUSTEP) || (MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_4)
GSIOThread *thread;
NSDate *when = [NSDate dateWithTimeIntervalSinceNow: timeout];
[classLock lock];
while ((thread = [threads lastObject]) != nil)
{
[thread performSelector: @selector(terminate:)
onThread: thread
withObject: when
waitUntilDone: NO];
[threads removeObjectIdenticalTo: thread];
}
[threads release];
[classLock unlock];
#endif
DESTROY(poolName);
[super dealloc];
}
- (id) init
{
#if defined(GNUSTEP) || (MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_4)
if ((self = [super init]) != nil)
{
threads = [NSMutableArray new];
threadClass = [GSIOThread class];
}
#else
[self release];
NSLog(@"WARNING, your OSX system is too old to use GSIOThreadPool");
return nil;
#endif
return self;
}
- (NSUInteger) maxThreads
{
return maxThreads;
}
- (NSString*) poolName
{
NSString *n;
[classLock lock];
n = RETAIN(poolName);
[classLock unlock];
return AUTORELEASE(n);
}
- (void) setPoolName: (NSString*)aName
{
NSString *s = nil;
if (aName)
{
s = AUTORELEASE([aName copy]);
NSAssert([s isKindOfClass: [NSString class]], NSInvalidArgumentException);
}
[classLock lock];
ASSIGN(poolName, s);
[classLock unlock];
}
- (void) setThreads: (NSUInteger)max
{
maxThreads = max;
}
- (void) setThreadClass: (Class)aClass
{
if (NO == [aClass isSubclassOfClass: [GSIOThread class]])
{
[NSException raise: NSInvalidArgumentException
format: @"Thread class must be a subclass of GSIOThread"];
}
threadClass = aClass;
}
- (void) setTimeout: (NSTimeInterval)t
{
timeout = t;
}
- (NSTimeInterval) timeout
{
return timeout;
}
- (void) unacquireThread: (NSThread*)aThread
{
[classLock lock];
if ([threads indexOfObjectIdenticalTo: aThread] != NSNotFound)
{
NSUInteger c;
c = [((GSIOThread*)aThread) _count];
if (0 == c)
{
[classLock unlock];
[NSException raise: NSInternalInconsistencyException
format: @"-unacquireThread: called too many times"];
}
[((GSIOThread*)aThread) _setCount: --c];
if (0 == c && [threads count] > maxThreads)
{
[aThread retain];
[threads removeObjectIdenticalTo: aThread];
[aThread performSelector: @selector(terminate:)
onThread: aThread
withObject: [NSDate date]
waitUntilDone: NO];
[aThread release];
}
}
[classLock unlock];
}
@end