Hi everyone
Since installing Snow Leopard a few weeks ago, I have been messing around with GCD.
In this function, I am passing a sets of files to be read. The function returns immediately to avoid blocking the GUI.
Each file is read in a synchronous queue loop, whereby the amount of progress is reported back to the delegate (i.e. the GUI) after each file has been dealt with. Maybe I should include here an option to cancel.
The order in which the files are processed can not be predicted, but every file is processed before reporting to the GUI that everything has finished.
Do you think I got everything right in this code? Is it correct, or did I fall into some (hidden) traps of concurrency?
Since installing Snow Leopard a few weeks ago, I have been messing around with GCD.
In this function, I am passing a sets of files to be read. The function returns immediately to avoid blocking the GUI.
Each file is read in a synchronous queue loop, whereby the amount of progress is reported back to the delegate (i.e. the GUI) after each file has been dealt with. Maybe I should include here an option to cancel.
The order in which the files are processed can not be predicted, but every file is processed before reporting to the GUI that everything has finished.
Do you think I got everything right in this code? Is it correct, or did I fall into some (hidden) traps of concurrency?
Code:
-(void) rawDataFromFiles:(NSArray *)files error:(NSError *)outError {
dispatch_queue_t a_queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0);
dispatch_async(a_queue,^{ //don't wait for me
//NSMutableArray *results = [NSMutableArray arrayWithCapacity:[files count]];
//__block NSMutableArray *results = [[NSMutableArray alloc] init]; //__block prevents retain++ of results in block -> crash
NSMutableArray *results = [[NSMutableArray alloc] initWithCapacity:[files count]];
__block int progress = 0;
void (^my_loop)(size_t) = ^(size_t i){ //what to do within loop
#warning todo: replace next line by file reading code
[results addObject:[NSNumber numberWithInt:i]]; //todo read data
dispatch_sync(dispatch_get_main_queue(),^{ //report progress, wait for me, run on main thread
[delegate importProgression:progress++ userInfo:nil];
});
};
dispatch_apply([files count], a_queue, my_loop); //wait for me
dispatch_async(dispatch_get_main_queue(),^{ //finishing up, don't wait for me, run on main thread
[delegate importDidFinish:[NSDictionary dictionaryWithObject:results forKey:@"results"]];
});
[results release];
});
outError = nil;
}