3

MyI have an NSOperationQueue with NSOperation objects in it

NSOperationQueue *aQueue = [[ NSOperationQueue alloc ] init];
[aQueue setMaxConcurrentOperationCount:3];

for (int index=0; index<=5; index++) {
    MYOperation *anOperation = [[MYOperation alloc] init];//MYOperation subclass from NSOperation
    [aQueue addOperation:anOperation];
}
NSLog(@"Number of Operations:%d",[aQueue operationCount]);//It gives 5 count

The queue only allows to executes 3 operation at a time(as per definition). When i try to add 4th operation, it adds to Queue, but the operation is never executed and it is discarded.

Ques: Why the Queue discards operation more than its concurrence values?

Meet
  • 4,904
  • 3
  • 24
  • 39
  • @MikePollard, Why the Queue discards operation more than its concurrence values? – Meet May 22 '13 at 07:13
  • Here's something from the class documentation: `The NSOperation class is an abstract class you use to encapsulate the code and data associated with a single task`. You can't use `NSOperation` class directly, you have to overwrite it and set some actions that it'll run. – alex-i May 22 '13 at 07:29
  • 2
    Where's the evidence that the 4th operation is discarded? What does it do with the fifth and sixth? – Mike Pollard May 22 '13 at 08:22
  • If possible, also show the source for `MyOperation`, and make sure the operations finish (in case they're concurrent, you set `isFinished` when they're done, otherwise they'll keep blocking the queue). – alex-i May 22 '13 at 08:42

1 Answers1

4

NSOperationQueue manages a thread to execute submitted operations on the background. (Since 10.6 using Grand Central Dispatch). Submitted operations are executed on a secondary thread by default.
You are immediately querying the operation queue after submitting a batch of operations - At that point the queue might not have started to execute the operations and therefore correctly reports a total operation count of 6.
If you add some delay before querying the queue, it might have already finished all operations and report a count of 0.

Sample code:

NSOperationQueue *aQueue = [[ NSOperationQueue alloc ] init];
[aQueue setMaxConcurrentOperationCount:3];

for (int index=0; index<=5; index++) {
    MYOperation *anOperation = [[MYOperation alloc] init];//MYOperation subclass from NSOperation
    [aQueue addOperation:anOperation];
}

double delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
    NSLog(@"Number of Operations:%d",[aQueue operationCount]);//It gives 5 count
});
Thomas Zoechling
  • 34,177
  • 3
  • 81
  • 112