The following method uploads some images to a remote server. I want them to be upload independent of each other (in parallel).
- (void)startUploadProcess {
for (int i = 0; i < [imageNames count]; i++) {
NSBlockOperation *blockOp = [NSBlockOperation blockOperationWithBlock:^{
[GlobalsFuncs uploadImageToServer:[[NSImage alloc] initWithContentsOfURL:[imagePaths objectAtIndex:i]] forSessionID:[[family SessionID] stringValue] withFilename:[imageNames objectAtIndex:i]];
}];
blockOp.completionBlock = ^{
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
[self afterUploadCompletion:i];
}];
};
[bgQueue addOperation:blockOp];
}
}
- (void)afterUploadCompletion:(NSInteger)pageNumber {
NSLog(@"%ld for sessionID : %@", (long)pageNumber, family.SessionID);
imagesUploaded++;
[progressIndicator incrementBy:progressDelta];
}
As you can see from the code above, I'm adding a call to the afterUploadCompletion
method for each image. In that method, I'm incrementing an integer that is a class instance variable. My question is if my code will ever cause a race condition? Basically, what I'm asking is if everything in the mainQueue
is executed serially?
Also, how can I make the NSOperationQueue *bgQueue
a parallel queue? I want blocks added to this queue to NOT wait for previous operations to complete.
Thanks a lot for your help!
As per Apple Documentation [NSOperationQueue mainQueue]
performs operation in serial manner:-
The [NSOperationQueue mainQueue]
returned queue executes one operation at a time on the app’s main thread. The execution of operations on the main thread is interleaved with the other tasks that must execute on the main thread, such as the servicing of events and the updating of an app’s user interface. The queue executes those operations in the run loop common modes, as represented by the NSRunLoopCommonModes constant.
Now if you want to execute the operation in concurrent or parallel manner. Refer the below sample:-
NSOperationQueue * queue = [[NSOperationQueue alloc] init];
NSOperation * nwOperation = [[yourOper alloc] init];
[queue addOperation:nwOperation];
So if you add multiple operations to a queue, they all execute in parallel on background threads, allowing your main thread to deal with the user interface. The queue will intelligently schedule the number of parallel operations based on the number of CPU cores your users have, thus effectively taking advantage of your users’ hardware.
EDIT:-
For more information about concurrent operations refer this Dave Dribin's blog.