Oolite
Loading...
Searching...
No Matches
OOAsyncWorkManager.m
Go to the documentation of this file.
1/*
2
3OOAsyncWorkManager.m
4
5
6Copyright (C) 2009-2013 Jens Ayton
7
8Permission is hereby granted, free of charge, to any person obtaining a copy
9of this software and associated documentation files (the "Software"), to deal
10in the Software without restriction, including without limitation the rights
11to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12copies of the Software, and to permit persons to whom the Software is
13furnished to do so, subject to the following conditions:
14
15The above copyright notice and this permission notice shall be included in all
16copies or substantial portions of the Software.
17
18THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24SOFTWARE.
25
26*/
27
30#import "OOAsyncQueue.h"
31#import "OOCPUInfo.h"
33#import "OONSOperation.h"
34
35#define USE_PTHREAD_ONCE (!OOLITE_WINDOWS)
36
37#if USE_PTHREAD_ONCE
38#include <pthread.h>
39#endif
40
42
43@interface NSThread (MethodsThatMayExistDependingOnSystem)
44
47
48@end
49
50/* OOAsyncWorkManagerInternal: shared superclass of our two implementations,
51 which implements shared functionality but is not itself concrete.
52*/
54@private
56
59}
60
61- (void)queueResult:(id<OOAsyncWorkTask>)task;
62
63- (void)noteTaskQueued:(id<OOAsyncWorkTask>)task;
64
65@end
66
67#if !OO_HAVE_NSOPERATION
68@interface OOManualDispatchAsyncWorkManager : OOAsyncWorkManagerInternal {
69@private
70 OOAsyncQueue* _taskQueue;
71}
72
73- (void)queueTask:(NSNumber*)threadNumber;
74
75@end
76#endif
77
79@private
81}
82
83#if !OO_HAVE_NSOPERATION
84+ (BOOL)canBeUsed;
85#endif
86
87- (void)dispatchTask:(id<OOAsyncWorkTask>)task;
88
89@end
90
91#if !USE_PTHREAD_ONCE
92static NSLock* sInitLock = nil;
93#endif
94
95static void InitAsyncWorkManager(void)
96{
97 NSCAssert(sSingleton == nil, @"Async Work Manager singleton not nil in one-time init");
98
99#if !OO_HAVE_NSOPERATION
100 if ([OOOperationQueueAsyncWorkManager canBeUsed]) {
102 }
103 if (sSingleton == nil) {
104 sSingleton = [[OOManualDispatchAsyncWorkManager alloc] init];
105 }
106#else
108#endif
109
110 if (sSingleton == nil) {
111 OOLog(@"asyncWorkManager.setUpDispatcher.failed", @"%@", @"***** FATAL ERROR: could not set up async work manager!");
112 exit(EXIT_FAILURE);
113 }
114
115 OOLog(@"asyncWorkManager.dispatchMethod", @"Selected async work manager: %@", [sSingleton class]);
116}
117
118@implementation OOAsyncWorkManager
119
120#if !USE_PTHREAD_ONCE
121+ (void)initialize
122{
123 if (sInitLock == nil) {
124 sInitLock = [[NSLock alloc] init];
125 NSAssert(sInitLock != nil, @"Async Work Manager init failed");
126 }
127}
128#endif
129
131{
132#if USE_PTHREAD_ONCE
133 static pthread_once_t once = PTHREAD_ONCE_INIT;
134 pthread_once(&once, InitAsyncWorkManager);
135 NSAssert(sSingleton != nil, @"Async Work Manager init failed");
136#else
137 [sInitLock lock];
138 if (sSingleton == nil) {
140 NSAssert(sSingleton != nil, @"Async Work Manager init failed");
141 }
142 [sInitLock unlock];
143#endif
144
145 return sSingleton;
146}
147
148+ (id)allocWithZone:(NSZone*)inZone
149{
150 if (sSingleton == nil) {
151 sSingleton = [super allocWithZone:inZone];
152 return sSingleton;
153 }
154 return nil;
155}
156
157- (void)dealloc
158{
159 abort();
160 [super dealloc];
161}
162
163- (oneway void)release
164{
165}
166
168{
169 return self;
170}
171
172- (NSUInteger)retainCount
173{
174 return UINT_MAX;
175}
176
177- (BOOL)addTask:(id<OOAsyncWorkTask>)task priority:(OOAsyncWorkPriority)priority
178{
180 return NO;
181}
182
187
188- (void)waitForTaskToComplete:(id<OOAsyncWorkTask>)task
189{
191 [NSException raise:NSInternalInconsistencyException format:@"%s called.", __PRETTY_FUNCTION__];
192}
193
194@end
195
196@implementation OOAsyncWorkManagerInternal
197
198- (id)init
199{
200 if ((self = [super init])) {
201 _readyQueue = [[OOAsyncQueue alloc] init];
202
203 if (_readyQueue == nil) {
204 [self release];
205 return nil;
206 }
207
209 _pendingOpsLock = [[NSLock alloc] init];
210
212 [self release];
213 return nil;
214 }
215 }
216
217 return self;
218}
219
221{
222 id next = nil;
223
224 [_pendingOpsLock lock];
225 for (;;) {
226 next = [_readyQueue tryDequeue];
227 if (next == nil)
228 break;
229
230 [_pendingCompletableOperations removeObject:next];
231 [next completeAsyncTask];
232 }
233 [_pendingOpsLock unlock];
234}
235
236- (void)waitForTaskToComplete:(id<OOAsyncWorkTask>)task
237{
238 if (task == nil)
239 return;
240
241#if OO_DEBUG
242 NSParameterAssert([(id)task respondsToSelector:@selector(completeAsyncTask)]);
243 NSAssert1(![NSThread respondsToSelector:@selector(isMainThread)] || [[NSThread self] isMainThread], @"%s can only be called from the main thread.", __PRETTY_FUNCTION__);
244#endif
245
246 [_pendingOpsLock lock];
247 BOOL exists = [_pendingCompletableOperations containsObject:task];
248 if (exists)
249 [_pendingCompletableOperations removeObject:task];
250 [_pendingOpsLock unlock];
251
252 if (!exists)
253 return;
254
255 id next = nil;
256 do {
257 // Dequeue a task and complete it.
258 next = [_readyQueue dequeue];
259 [_pendingOpsLock lock];
260 [_pendingCompletableOperations removeObject:next];
261 [_pendingOpsLock unlock];
262
263 [next completeAsyncTask];
264
265 } while (next != task); // We don't control order, so keep looking until we get the one we care about.
266}
267
268- (void)queueResult:(id<OOAsyncWorkTask>)task
269{
270 if ([task respondsToSelector:@selector(completeAsyncTask)]) {
271 [_readyQueue enqueue:task];
272 }
273}
274
275- (void)noteTaskQueued:(id<OOAsyncWorkTask>)task
276{
277 [_pendingOpsLock lock];
278 [_pendingCompletableOperations addObject:task];
279 [_pendingOpsLock unlock];
280}
281
282@end
283
284/******* OOManualDispatchAsyncWorkManager - manual thread management *******/
285
286enum {
288};
289
290#if !OO_HAVE_NSOPERATION
291@implementation OOManualDispatchAsyncWorkManager
292
293- (id)init
294{
295 if ((self = [super init])) {
296 // Set up work queue.
297 _taskQueue = [[OOAsyncQueue alloc] init];
298 if (_taskQueue == nil) {
299 [self release];
300 return nil;
301 }
302
303 // Set up loading threads.
304 NSUInteger threadCount, threadNumber = 1;
305#if OO_DEBUG
306 threadCount = kMaxWorkThreads;
307#else
308 threadCount = MIN(OOCPUCount(), (unsigned)kMaxWorkThreads);
309#endif
310 do {
311 [NSThread detachNewThreadSelector:@selector(queueTask:) toTarget:self withObject:[NSNumber numberWithInt:threadNumber++]];
312 } while (--threadCount > 0);
313 }
314
315 return self;
316}
317
318- (BOOL)addTask:(id<OOAsyncWorkTask>)task priority:(OOAsyncWorkPriority)priority
319{
320 if (EXPECT_NOT(task == nil))
321 return NO;
322
323 [super noteTaskQueued:task];
324
325 // Priority is ignored.
326 return [_taskQueue enqueue:task];
327}
328
329- (void)queueTask:(NSNumber*)threadNumber
330{
331 NSAutoreleasePool *rootPool = nil, *pool = nil;
332
333 rootPool = [[NSAutoreleasePool alloc] init];
334
335 [NSThread setThreadPriority:0.5];
336 [NSThread ooSetCurrentThreadName:[NSString stringWithFormat:@"OOAsyncWorkManager thread %@", threadNumber]];
337
338 for (;;) {
339 pool = [[NSAutoreleasePool alloc] init];
340
341 id<OOAsyncWorkTask> task = [_taskQueue dequeue];
342 @try {
343 [task performAsyncTask];
344 }
345 @catch (id exception) {
346 }
347 [self queueResult:task];
348
349 [pool release];
350 }
351
352 [rootPool release];
353}
354
355@end
356#endif
357
358/******* OOOperationQueueAsyncWorkManager - dispatch through NSOperationQueue if available *******/
359
360@implementation OOOperationQueueAsyncWorkManager
361
362#if !OO_HAVE_NSOPERATION
363+ (BOOL)canBeUsed
364{
365 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"disable-operation-queue-work-manager"])
366 return NO;
367 return [OONSInvocationOperationClass() class] != Nil;
368}
369#endif
370
371- (id)init
372{
373 if ((self = [super init])) {
374 _operationQueue = [[OONSOperationQueueClass() alloc] init];
375
376 if (_operationQueue == nil) {
377 [self release];
378 return nil;
379 }
380 }
381
382 return self;
383}
384
385- (void)dealloc
386{
387 [_operationQueue release];
388
389 [super dealloc];
390}
391
392- (BOOL)addTask:(id<OOAsyncWorkTask>)task priority:(OOAsyncWorkPriority)priority
393{
394 if (EXPECT_NOT(task == nil))
395 return NO;
396
397 id operation = [[OONSInvocationOperationClass() alloc] initWithTarget:self selector:@selector(dispatchTask:) object:task];
398 if (operation == nil)
399 return NO;
400
401 if (priority == kOOAsyncPriorityLow)
402 [operation setQueuePriority:OONSOperationQueuePriorityLow];
403 else if (priority == kOOAsyncPriorityHigh)
404 [operation setQueuePriority:OONSOperationQueuePriorityHigh];
405
406 [_operationQueue addOperation:operation];
407 [operation release];
408
409 [super noteTaskQueued:task];
410 return YES;
411}
412
413- (void)dispatchTask:(id<OOAsyncWorkTask>)task
414{
415 @try {
416 [task performAsyncTask];
417 }
418 @catch (id exception) {
419 }
420 [self queueResult:task];
421}
422
423@end
OOAsyncWorkPriority
@ kOOAsyncPriorityLow
@ kOOAsyncPriorityHigh
@ kMaxWorkThreads
static void InitAsyncWorkManager(void)
NSUInteger OOCPUCount(void)
Definition OOCPUInfo.m:99
#define EXPECT_NOT(x)
#define OOLogGenericSubclassResponsibility()
Definition OOLogging.h:141
#define OOLog(class, format,...)
Definition OOLogging.h:84
#define MIN(A, B)
Definition OOMaths.h:91
#define OONSOperationQueue
static OONullTexture * sSingleton
return nil
BOOL enqueue:(id object)
NSMutableSet * _pendingCompletableOperations
void noteTaskQueued:(id< OOAsyncWorkTask > task)
void queueResult:(id< OOAsyncWorkTask > task)
OOAsyncWorkManager * sharedAsyncWorkManager()