Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Beginning iOS5 Development.pdf
Скачиваний:
7
Добавлен:
09.05.2015
Размер:
15.6 Mб
Скачать

538

CHAPTER 15: Grand Central Dispatch, Background Processing, and You

Concurrent Blocks

So far, so good, but we’re not quite finished yet! The sharp-eyed among you will notice that after going through these motions, we still haven’t really changed the basic sequential layout of our algorithm (if you can even call this simple list of steps an algorithm). All that we’re doing is moving a chunk of this method to a background thread and then finishing up in the main thread. The Xcode console output proves it: this work takes ten seconds to run, just as it did at the outset. The 900-pound gorilla in the room is that calculateFirstResult: and calculateSecondResult: don’t need to be performed in sequence, and doing them concurrently could give us a substantial speedup.

Fortunately, GCD has a way to accomplish this by using what’s called a dispatch group. All blocks that are dispatched asynchronously within the context of a group, via the dispatch_group_async() function, are set loose to execute as fast as they can, including being distributed to multiple threads for concurrent execution, if possible. We can also use dispatch_group_notify() to specify an additional block that will be executed when all the blocks in the group have been run to completion.

Make the following changes to your copy of doWork:. Again, make sure you get that trailing bit of curly brace and parenthesis.

- (IBAction)doWork:(id)sender {

NSDate *startTime = [NSDate date]; dispatch_async(dispatch_get_global_queue(0, 0), ^{

NSString *fetchedData = [self fetchSomethingFromServer]; NSString *processedData = [self processData:fetchedData];

NSString *firstResult = [self calculateFirstResult:processedData]; NSString *secondResult = [self calculateSecondResult:processedData];

__block NSString *firstResult; __block NSString *secondResult;

dispatch_group_t group = dispatch_group_create(); dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{

firstResult = [self calculateFirstResult:processedData];

});

dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{ secondResult = [self calculateSecondResult:processedData];

});

dispatch_group_notify(group, dispatch_get_global_queue(0, 0), ^{

NSString *resultsSummary = [NSString stringWithFormat:

@"First: [%@]\nSecond: [%@]", firstResult, secondResult];

dispatch_async(dispatch_get_main_queue(), ^{ startButton.enabled = YES; startButton.alpha = 1.0;

[spinner stopAnimating]; resultsTextView.text = resultsSummary;

});

NSDate *endTime = [NSDate date]; NSLog(@"Completed in %f seconds",

[endTime timeIntervalSinceDate:startTime]);

});

});

}

www.it-ebooks.info

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]