Search code examples
iphoneiosmultithreadingnsoperationnsoperationqueue

Setting concurrent operation for NSOperationQueue causes only that number of operation


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?


Solution

  • 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
    });