-
Notifications
You must be signed in to change notification settings - Fork 279
/
NSOperation.m
1152 lines (1031 loc) · 27.8 KB
/
NSOperation.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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**Implementation for NSOperation for GNUStep
Copyright (C) 2008-2023 Free Software Foundation, Inc.
Written by: Gregory Casamento <greg.casamento@gmail.com>
Written by: Richard Frith-Macdonald <rfm@gnu.org>
This file is part of the GNUstep Base 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 2 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., 51 Franklin Street, Fifth Floor,
Boston, MA 02110 USA.
<title>NSOperation class reference</title>
Created: 2008-06-08 11:38:33 +0100 (Sun, 08 Jun 2008)
*/
#import "common.h"
#import "Foundation/NSLock.h"
#define GS_NSOperation_IVARS \
NSRecursiveLock *lock; \
NSConditionLock *cond; \
NSOperationQueuePriority priority; \
double threadPriority; \
BOOL cancelled; \
BOOL concurrent; \
BOOL executing; \
BOOL finished; \
BOOL blocked; \
BOOL ready; \
NSMutableArray *dependencies; \
id completionBlock;
#define GS_NSOperationQueue_IVARS \
NSRecursiveLock *lock; \
NSConditionLock *cond; \
NSMutableArray *operations; \
NSMutableArray *waiting; \
NSMutableArray *starting; \
NSString *name; \
BOOL suspended; \
NSInteger executing; \
NSInteger threadCount; \
NSInteger maxThreads;
#import "Foundation/NSOperation.h"
#import "Foundation/NSArray.h"
#import "Foundation/NSAutoreleasePool.h"
#import "Foundation/NSDictionary.h"
#import "Foundation/NSEnumerator.h"
#import "Foundation/NSException.h"
#import "Foundation/NSKeyValueObserving.h"
#import "Foundation/NSThread.h"
#import "GNUstepBase/NSArray+GNUstepBase.h"
#import "GSPrivate.h"
#define GSInternal NSOperationInternal
#include "GSInternal.h"
GS_PRIVATE_INTERNAL(NSOperation)
static void *isFinishedCtxt = (void*)"isFinished";
static void *isReadyCtxt = (void*)"isReady";
static void *queuePriorityCtxt = (void*)"queuePriority";
static NSArray *empty = nil;
@interface NSOperation (Private)
- (void) _finish;
- (void) _updateReadyState;
@end
@implementation NSOperation
+ (BOOL) automaticallyNotifiesObserversForKey: (NSString*)theKey
{
/* Handle all KVO manually
*/
return NO;
}
+ (void) initialize
{
empty = [NSArray new];
RELEASE([NSObject leakAt: &empty]);
}
- (void) addDependency: (NSOperation *)op
{
if (NO == [op isKindOfClass: [NSOperation class]])
{
[NSException raise: NSInvalidArgumentException
format: @"[%@-%@] dependency is not an NSOperation",
NSStringFromClass([self class]), NSStringFromSelector(_cmd)];
}
if (op == self)
{
[NSException raise: NSInvalidArgumentException
format: @"[%@-%@] attempt to add dependency on self",
NSStringFromClass([self class]), NSStringFromSelector(_cmd)];
}
[internal->lock lock];
if (internal->dependencies == nil)
{
internal->dependencies = [[NSMutableArray alloc] initWithCapacity: 5];
}
NS_DURING
{
if (NSNotFound == [internal->dependencies indexOfObjectIdenticalTo: op])
{
[self willChangeValueForKey: @"dependencies"];
[internal->dependencies addObject: op];
/* We only need to watch for changes if it's possible for them to
* happen and make a difference.
*/
if (NO == [op isFinished]
&& NO == [self isCancelled]
&& NO == [self isExecuting]
&& NO == [self isFinished])
{
/* Can change readiness if we are neither cancelled nor
* executing nor finished. So we need to observe for the
* finish of the dependency.
*/
[op addObserver: self
forKeyPath: @"isFinished"
options: NSKeyValueObservingOptionNew
context: isFinishedCtxt];
if (internal->ready == YES)
{
/* The new dependency stops us being ready ...
* change state.
*/
[self willChangeValueForKey: @"isReady"];
internal->ready = NO;
[self didChangeValueForKey: @"isReady"];
}
}
[self didChangeValueForKey: @"dependencies"];
}
}
NS_HANDLER
{
[internal->lock unlock];
NSLog(@"Problem adding dependency: %@", localException);
return;
}
NS_ENDHANDLER
[internal->lock unlock];
}
- (void) cancel
{
if (NO == internal->cancelled && NO == [self isFinished])
{
[internal->lock lock];
if (NO == internal->cancelled && NO == [self isFinished])
{
NS_DURING
{
[self willChangeValueForKey: @"isCancelled"];
internal->cancelled = YES;
if (NO == internal->ready)
{
[self willChangeValueForKey: @"isReady"];
internal->ready = YES;
[self didChangeValueForKey: @"isReady"];
}
[self didChangeValueForKey: @"isCancelled"];
}
NS_HANDLER
{
[internal->lock unlock];
NSLog(@"Problem cancelling operation: %@", localException);
return;
}
NS_ENDHANDLER
}
[internal->lock unlock];
}
}
- (GSOperationCompletionBlock) completionBlock
{
return (GSOperationCompletionBlock)internal->completionBlock;
}
- (void) dealloc
{
if (internal != nil)
{
NSOperation *op;
if (!internal->finished)
{
[self removeObserver: self forKeyPath: @"isFinished"];
}
while ((op = [internal->dependencies lastObject]) != nil)
{
[self removeDependency: op];
}
RELEASE(internal->dependencies);
RELEASE(internal->cond);
RELEASE(internal->lock);
RELEASE(internal->completionBlock);
GS_DESTROY_INTERNAL(NSOperation);
}
[super dealloc];
}
- (NSArray *) dependencies
{
NSArray *a;
if (internal->dependencies == nil)
{
a = empty; // OSX return an empty array
}
else
{
[internal->lock lock];
a = [NSArray arrayWithArray: internal->dependencies];
[internal->lock unlock];
}
return a;
}
- (id) init
{
if ((self = [super init]) != nil)
{
GS_CREATE_INTERNAL(NSOperation);
internal->priority = NSOperationQueuePriorityNormal;
internal->threadPriority = 0.5;
internal->ready = YES;
internal->lock = [NSRecursiveLock new];
[internal->lock setName:
[NSString stringWithFormat: @"lock-for-opqueue-%p", self]];
internal->cond = [[NSConditionLock alloc] initWithCondition: 0];
[internal->cond setName:
[NSString stringWithFormat: @"cond-for-opqueue-%p", self]];
[self addObserver: self
forKeyPath: @"isFinished"
options: NSKeyValueObservingOptionNew
context: isFinishedCtxt];
}
return self;
}
- (BOOL) isCancelled
{
return internal->cancelled;
}
- (BOOL) isExecuting
{
return internal->executing;
}
- (BOOL) isFinished
{
return internal->finished;
}
- (BOOL) isConcurrent
{
return internal->concurrent;
}
- (BOOL) isReady
{
return internal->ready;
}
- (void) main
{
return; // OSX default implementation does nothing
}
- (void) observeValueForKeyPath: (NSString *)keyPath
ofObject: (id)object
change: (NSDictionary *)change
context: (void *)context
{
NSOperation *op = object;
if (NO == [op isFinished])
{
return;
}
if (object == self)
{
[internal->lock lock];
/* We only observe isFinished changes, and we can remove self as an
* observer once we know the operation has finished since it can never
* become unfinished.
*/
[object removeObserver: self forKeyPath: @"isFinished"];
/* Concurrent operations: Call completion block and set internal finished
* state so we don't try removing the observer again in -dealloc. */
if (YES == [self isConcurrent])
{
internal->finished = YES;
CALL_BLOCK_NO_ARGS(
((GSOperationCompletionBlock)internal->completionBlock));
}
/* We have finished and need to unlock the condition lock so that
* any waiting thread can continue.
*/
[internal->cond lock];
[internal->cond unlockWithCondition: 1];
[internal->lock unlock];
}
else
{
/* Some dependency has finished ...
*/
[self _updateReadyState];
}
}
- (NSOperationQueuePriority) queuePriority
{
return internal->priority;
}
- (void) removeDependency: (NSOperation *)op
{
[internal->lock lock];
NS_DURING
{
if (NSNotFound != [internal->dependencies indexOfObjectIdenticalTo: op])
{
[op removeObserver: self forKeyPath: @"isFinished"];
[self willChangeValueForKey: @"dependencies"];
[internal->dependencies removeObject: op];
if (NO == internal->ready)
{
/* The dependency may cause us to become ready ...
*/
[self _updateReadyState];
}
[self didChangeValueForKey: @"dependencies"];
}
}
NS_HANDLER
{
[internal->lock unlock];
NSLog(@"Problem removing dependency: %@", localException);
return;
}
NS_ENDHANDLER
[internal->lock unlock];
}
- (void) setCompletionBlock: (GSOperationCompletionBlock)aBlock
{
ASSIGNCOPY(internal->completionBlock, (id)aBlock);
}
- (void) setQueuePriority: (NSOperationQueuePriority)pri
{
if (pri <= NSOperationQueuePriorityVeryLow)
pri = NSOperationQueuePriorityVeryLow;
else if (pri <= NSOperationQueuePriorityLow)
pri = NSOperationQueuePriorityLow;
else if (pri < NSOperationQueuePriorityHigh)
pri = NSOperationQueuePriorityNormal;
else if (pri < NSOperationQueuePriorityVeryHigh)
pri = NSOperationQueuePriorityHigh;
else
pri = NSOperationQueuePriorityVeryHigh;
if (pri != internal->priority)
{
[internal->lock lock];
if (pri != internal->priority)
{
NS_DURING
{
[self willChangeValueForKey: @"queuePriority"];
internal->priority = pri;
[self didChangeValueForKey: @"queuePriority"];
}
NS_HANDLER
{
[internal->lock unlock];
NSLog(@"Problem setting priority: %@", localException);
return;
}
NS_ENDHANDLER
}
[internal->lock unlock];
}
}
- (void) setThreadPriority: (double)pri
{
if (pri > 1) pri = 1;
else if (pri < 0) pri = 0;
internal->threadPriority = pri;
}
- (void) start
{
ENTER_POOL
double prio = [NSThread threadPriority];
AUTORELEASE(RETAIN(self)); // Make sure we exist while running.
[internal->lock lock];
NS_DURING
{
if (YES == [self isExecuting])
{
[NSException raise: NSInvalidArgumentException
format: @"[%@-%@] called on executing operation",
NSStringFromClass([self class]), NSStringFromSelector(_cmd)];
}
if (YES == [self isFinished])
{
[NSException raise: NSInvalidArgumentException
format: @"[%@-%@] called on finished operation",
NSStringFromClass([self class]), NSStringFromSelector(_cmd)];
}
if (NO == [self isReady])
{
[NSException raise: NSInvalidArgumentException
format: @"[%@-%@] called on operation which is not ready",
NSStringFromClass([self class]), NSStringFromSelector(_cmd)];
}
if (NO == internal->executing)
{
[self willChangeValueForKey: @"isExecuting"];
internal->executing = YES;
[self didChangeValueForKey: @"isExecuting"];
}
}
NS_HANDLER
{
[internal->lock unlock];
[localException raise];
}
NS_ENDHANDLER
[internal->lock unlock];
NS_DURING
{
if (NO == [self isCancelled])
{
[NSThread setThreadPriority: internal->threadPriority];
[self main];
}
}
NS_HANDLER
{
[NSThread setThreadPriority: prio];
[localException raise];
}
NS_ENDHANDLER;
[self _finish];
LEAVE_POOL
}
- (double) threadPriority
{
return internal->threadPriority;
}
- (void) waitUntilFinished
{
[internal->cond lockWhenCondition: 1]; // Wait for finish
[internal->cond unlockWithCondition: 1]; // Signal any other watchers
}
@end
@implementation NSOperation (Private)
/* NB code calling this method must ensure that the receiver is retained
* until after the method returns.
*/
- (void) _finish
{
[internal->lock lock];
if (NO == internal->finished)
{
if (YES == internal->executing)
{
[self willChangeValueForKey: @"isExecuting"];
[self willChangeValueForKey: @"isFinished"];
internal->executing = NO;
internal->finished = YES;
[self didChangeValueForKey: @"isFinished"];
[self didChangeValueForKey: @"isExecuting"];
}
else
{
[self willChangeValueForKey: @"isFinished"];
internal->finished = YES;
[self didChangeValueForKey: @"isFinished"];
}
CALL_BLOCK_NO_ARGS(
((GSOperationCompletionBlock)internal->completionBlock));
}
[internal->lock unlock];
}
- (void) _updateReadyState
{
[internal->lock lock];
if (NO == internal->ready)
{
NSEnumerator *en;
NSOperation *op;
/* After a dependency has finished or was removed we need to check
* to see if we are now ready.
* This is protected by locks so that an update due to an observed
* change in one thread won't interrupt anything in another thread.
*/
en = [internal->dependencies objectEnumerator];
while ((op = [en nextObject]) != nil)
{
if (NO == [op isFinished])
break;
}
if (op == nil)
{
[self willChangeValueForKey: @"isReady"];
internal->ready = YES;
[self didChangeValueForKey: @"isReady"];
}
}
[internal->lock unlock];
}
@end
@implementation NSBlockOperation
+ (instancetype) blockOperationWithBlock: (GSBlockOperationBlock)block
{
NSBlockOperation *op = [[self alloc] init];
[op addExecutionBlock: block];
return AUTORELEASE(op);
}
- (void) addExecutionBlock: (GSBlockOperationBlock)block
{
id blockCopy = (id)Block_copy(block);
[_executionBlocks addObject: blockCopy];
RELEASE(blockCopy);
}
- (void) dealloc
{
RELEASE(_executionBlocks);
[super dealloc];
}
- (NSArray *) executionBlocks
{
return _executionBlocks;
}
- (id) init
{
self = [super init];
if (self != nil)
{
_executionBlocks = [[NSMutableArray alloc] initWithCapacity: 1];
}
return self;
}
- (void) main
{
NSEnumerator *en = [[self executionBlocks] objectEnumerator];
GSBlockOperationBlock theBlock;
while ((theBlock = (GSBlockOperationBlock)[en nextObject]) != NULL)
{
CALL_NON_NULL_BLOCK_NO_ARGS(theBlock);
}
}
@end
#undef GSInternal
#define GSInternal NSOperationQueueInternal
#include "GSInternal.h"
GS_PRIVATE_INTERNAL(NSOperationQueue)
@interface NSOperationQueue (Private)
- (void) _execute;
- (void) _thread;
- (void) observeValueForKeyPath: (NSString *)keyPath
ofObject: (id)object
change: (NSDictionary *)change
context: (void *)context;
@end
static NSInteger maxConcurrent = 8; // Thread pool size
static NSComparisonResult
sortFunc(id o1, id o2, void *ctxt)
{
NSOperationQueuePriority p1 = [o1 queuePriority];
NSOperationQueuePriority p2 = [o2 queuePriority];
if (p1 < p2) return NSOrderedDescending;
if (p1 > p2) return NSOrderedAscending;
return NSOrderedSame;
}
static NSString *threadKey = @"NSOperationQueue";
static NSOperationQueue *mainQueue = nil;
@implementation NSOperationQueue
+ (id) currentQueue
{
if ([NSThread isMainThread])
{
return mainQueue;
}
return [[[NSThread currentThread] threadDictionary] objectForKey: threadKey];
}
+ (void) initialize
{
if (nil == mainQueue)
{
mainQueue = [self new];
}
}
+ (id) mainQueue
{
return mainQueue;
}
- (void) addOperation: (NSOperation *)op
{
if (op == nil || NO == [op isKindOfClass: [NSOperation class]])
{
[NSException raise: NSInvalidArgumentException
format: @"[%@-%@] object is not an NSOperation",
NSStringFromClass([self class]), NSStringFromSelector(_cmd)];
}
[internal->lock lock];
if (NSNotFound == [internal->operations indexOfObjectIdenticalTo: op]
&& NO == [op isFinished])
{
[op addObserver: self
forKeyPath: @"isReady"
options: NSKeyValueObservingOptionNew
context: isReadyCtxt];
[self willChangeValueForKey: @"operations"];
[self willChangeValueForKey: @"operationCount"];
[internal->operations addObject: op];
[self didChangeValueForKey: @"operationCount"];
[self didChangeValueForKey: @"operations"];
if (YES == [op isReady])
{
[self observeValueForKeyPath: @"isReady"
ofObject: op
change: nil
context: isReadyCtxt];
}
}
[internal->lock unlock];
}
- (void) addOperationWithBlock: (GSBlockOperationBlock)block
{
NSBlockOperation *bop = [NSBlockOperation blockOperationWithBlock: block];
[self addOperation: bop];
}
- (void) addOperations: (NSArray *)ops
waitUntilFinished: (BOOL)shouldWait
{
NSUInteger total;
NSUInteger index;
if (ops == nil || NO == [ops isKindOfClass: [NSArray class]])
{
[NSException raise: NSInvalidArgumentException
format: @"[%@-%@] object is not an NSArray",
NSStringFromClass([self class]), NSStringFromSelector(_cmd)];
}
total = [ops count];
if (total > 0)
{
BOOL invalidArg = NO;
NSUInteger toAdd = total;
GS_BEGINITEMBUF(buf, total, id)
[ops getObjects: buf];
for (index = 0; index < total; index++)
{
NSOperation *op = buf[index];
if (NO == [op isKindOfClass: [NSOperation class]])
{
invalidArg = YES;
toAdd = 0;
break;
}
if (YES == [op isFinished])
{
buf[index] = nil;
toAdd--;
}
}
if (toAdd > 0)
{
[internal->lock lock];
[self willChangeValueForKey: @"operationCount"];
[self willChangeValueForKey: @"operations"];
for (index = 0; index < total; index++)
{
NSOperation *op = buf[index];
if (op == nil)
{
continue; // Not added
}
if (NSNotFound
!= [internal->operations indexOfObjectIdenticalTo: op])
{
buf[index] = nil; // Not added
toAdd--;
continue;
}
[op addObserver: self
forKeyPath: @"isReady"
options: NSKeyValueObservingOptionNew
context: isReadyCtxt];
[internal->operations addObject: op];
if (NO == [op isReady])
{
buf[index] = nil; // Not yet ready
}
}
[self didChangeValueForKey: @"operationCount"];
[self didChangeValueForKey: @"operations"];
for (index = 0; index < total; index++)
{
NSOperation *op = buf[index];
if (op != nil)
{
[self observeValueForKeyPath: @"isReady"
ofObject: op
change: nil
context: isReadyCtxt];
}
}
[internal->lock unlock];
}
GS_ENDITEMBUF()
if (YES == invalidArg)
{
[NSException raise: NSInvalidArgumentException
format: @"[%@-%@] object at index %"PRIuPTR" is not an NSOperation",
NSStringFromClass([self class]), NSStringFromSelector(_cmd),
index];
}
}
if (YES == shouldWait)
{
[self waitUntilAllOperationsAreFinished];
}
}
- (void) cancelAllOperations
{
[[self operations] makeObjectsPerformSelector: @selector(cancel)];
}
- (void) dealloc
{
[self cancelAllOperations];
DESTROY(internal->operations);
DESTROY(internal->starting);
DESTROY(internal->waiting);
DESTROY(internal->name);
DESTROY(internal->cond);
DESTROY(internal->lock);
GS_DESTROY_INTERNAL(NSOperationQueue);
[super dealloc];
}
- (id) init
{
if ((self = [super init]) != nil)
{
GS_CREATE_INTERNAL(NSOperationQueue);
internal->suspended = NO;
internal->maxThreads = NSOperationQueueDefaultMaxConcurrentOperationCount;
internal->operations = [NSMutableArray new];
internal->starting = [NSMutableArray new];
internal->waiting = [NSMutableArray new];
internal->lock = [NSRecursiveLock new];
[internal->lock setName:
[NSString stringWithFormat: @"lock-for-op-%p", self]];
internal->cond = [[NSConditionLock alloc] initWithCondition: 0];
[internal->cond setName:
[NSString stringWithFormat: @"cond-for-op-%p", self]];
}
return self;
}
- (BOOL) isSuspended
{
return internal->suspended;
}
- (NSInteger) maxConcurrentOperationCount
{
return internal->maxThreads;
}
- (NSString*) name
{
NSString *s;
[internal->lock lock];
if (internal->name == nil)
{
internal->name
= [[NSString alloc] initWithFormat: @"NSOperation %p", self];
}
s = RETAIN(internal->name);
[internal->lock unlock];
return AUTORELEASE(s);
}
- (NSUInteger) operationCount
{
NSUInteger c;
[internal->lock lock];
c = [internal->operations count];
[internal->lock unlock];
return c;
}
- (NSArray *) operations
{
NSArray *a;
[internal->lock lock];
a = [NSArray arrayWithArray: internal->operations];
[internal->lock unlock];
return a;
}
- (void) setMaxConcurrentOperationCount: (NSInteger)cnt
{
if (cnt < 0
&& cnt != NSOperationQueueDefaultMaxConcurrentOperationCount)
{
[NSException raise: NSInvalidArgumentException
format: @"[%@-%@] cannot set negative (%"PRIdPTR") count",
NSStringFromClass([self class]), NSStringFromSelector(_cmd), cnt];
}
[internal->lock lock];
if (cnt != internal->maxThreads)
{
[self willChangeValueForKey: @"maxConcurrentOperationCount"];
internal->maxThreads = cnt;
[self didChangeValueForKey: @"maxConcurrentOperationCount"];
}
[internal->lock unlock];
[self _execute];
}
- (void) setName: (NSString*)s
{
if (s == nil) s = @"";
[internal->lock lock];
if (NO == [internal->name isEqual: s])
{
[self willChangeValueForKey: @"name"];
RELEASE(internal->name);
internal->name = [s copy];
[self didChangeValueForKey: @"name"];
}
[internal->lock unlock];
}
- (void) setSuspended: (BOOL)flag
{
[internal->lock lock];
if (flag != internal->suspended)
{
[self willChangeValueForKey: @"suspended"];
internal->suspended = flag;
[self didChangeValueForKey: @"suspended"];
}
[internal->lock unlock];
[self _execute];
}
- (void) waitUntilAllOperationsAreFinished
{
NSOperation *op;
[internal->lock lock];
while ((op = [internal->operations lastObject]) != nil)
{
RETAIN(op);
[internal->lock unlock];
[op waitUntilFinished];
RELEASE(op);
[internal->lock lock];
}
[internal->lock unlock];
}
@end
@implementation NSOperationQueue (Private)
- (void) observeValueForKeyPath: (NSString *)keyPath
ofObject: (id)object
change: (NSDictionary *)change
context: (void *)context
{
/* We observe three properties in sequence ...
* isReady (while we wait for an operation to be ready)
* queuePriority (when priority of a ready operation may change)
* isFinished (to see if an executing operation is over).
*/
if (context == isFinishedCtxt)
{
NSOperation *op = object;
if (YES == [op isFinished])
{
[internal->lock lock];
internal->executing--;
[object removeObserver: self forKeyPath: @"isFinished"];
[internal->lock unlock];
[self willChangeValueForKey: @"operations"];
[self willChangeValueForKey: @"operationCount"];
[internal->lock lock];
[internal->operations removeObjectIdenticalTo: object];
[internal->lock unlock];
[self didChangeValueForKey: @"operationCount"];
[self didChangeValueForKey: @"operations"];
}
}
else if (context == queuePriorityCtxt || context == isReadyCtxt)
{
NSInteger pos;
[internal->lock lock];
if (context == queuePriorityCtxt)
{
[internal->waiting removeObjectIdenticalTo: object];
}
if (context == isReadyCtxt)
{
[object removeObserver: self forKeyPath: @"isReady"];
[object addObserver: self
forKeyPath: @"queuePriority"
options: NSKeyValueObservingOptionNew
context: queuePriorityCtxt];
}
pos = [internal->waiting insertionPosition: object
usingFunction: sortFunc
context: 0];
[internal->waiting insertObject: object atIndex: pos];
[internal->lock unlock];
}
[self _execute];
}