一、What is GCD?
GCD is the marketing name for libdispatch, Apple’s library that provides support for concurrent code execution on multicore hardware on iOS and OS X. It offers the following benefits:
GCD can improve your app’s responsiveness by helping you defer computationally expensive tasks and run them in the background.
GCD provides an easier concurrency model than locks and threads and helps to avoid concurrency bugs.
GCD can potentially optimize your code with higher performance primitives for common patterns such as singletons.
二、Queue Types
First, the system provides you with a special serial queue known as the main queue. Like any serial queue, tasks in this queue execute one at a time. However, it’s guaranteed that all tasks will execute on the main thread, which is the only thread allowed to update your UI. This queue is the one to use for sending messages to UIViews or posting notifications.
The system also provides you with several concurrent queues. These are known as the Global Dispatch Queues. There are currently four global queues of different priority: background, low, default, and high. Be aware that Apple’s APIs also uses these queues, so any tasks you add won’t be the only ones on these queues.
Finally, you can also create your own custom serial or concurrent queues. That means you have at least five queues at your disposal: the main queue, four global dispatch queues, plus any custom queues that you add to the mix!
三、 the various queue types with dispatch_async
Here’s a quick guide of how and when to use the various queue types with dispatch_async:
*** Custom Serial Queue: A good choice when you want to perform background work serially and track it. This eliminates resource contention since you know only one task at a time is executing. Note that if you need the data from a method, you must inline another block to retrieve it or consider using dispatch_sync.
*** Main Queue (Serial): This is a common choice to update the UI after completing work in a task on a concurrent queue. To do this, you’ll code one block inside another. As well, if you’re in the main queue and call dispatch_async targeting the main queue, you can guarantee that this new task will execute sometime after the current method finishes.
*** Concurrent Queue: This is a common choice to perform non-UI work in the background.
四、Making Your Singletons Thread-Safe
+ (instancetype)sharedManager {
static PhotoManager *sharedPhotoManager = nil;
if (!sharedPhotoManager) {
sharedPhotoManager = [[PhotoManager alloc] init];
sharedPhotoManager->_photosArray = [[NSMutableArray]
}
return sharedPhotoManager;
}
The code is rather simple in its current state; you create a singleton and instantiate a private NSMutableArray property named photosArray.
However, the if condition branch is not thread safe; if you invoke this method multiple times, there’s a possibility that one thread (call it Thread-A) could enter the if
block and a context switch could occur before sharedPhotoManager is allocated. Then another thread (Thread-B) could enter the if, allocate an instance of the singleton, then exit.
When the system context switches back to Thread-A, you’ll then allocate another instance of the singleton, then exit. At that point you have two instances of a singleton — which is not what you want!
To force this condition to happen, replace sharedManager in PhotoManager.m with the following implementation:
+ (instancetype)sharedManager {
static PhotoManager *sharedPhotoManager = nil;
if (!sharedPhotoManager) {
[[NSThread] sleepForTimeInterval:2];
sharedPhotoManager = [[PhotoManager alloc] init];
NSLog(@"Singleton has memory address at: %@", sharedPhotoManager);
[[NSThread] sleepForTimeInterval:2];
sharedPhotoManager->_photosArray = [[NSMutableArray] array]; }
return sharedPhotoManager;
}
In the code above you’re forcing a context switch to happen with NSThread’s sleepForTimeInterval: class method.
五、Dispatch Groups
The GCD API provides two ways to be notified when all events in the group have completed.
The first one, dispatch_group_wait, is a function that blocks your current thread and waits until either all the tasks in the group have completed, or until a timeout occurs. This is exactly what you want in this case.
eg.
- (void)downloadPhotosWithCompletionBlock:(BatchPhotoDownloadingCompletionBlock)completionBlock
{ dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ // 1
__block NSError *error;
dispatch_group_t downloadGroup = dispatch_group_create(); // 2
for (NSInteger i = 0; i < 3; i++) {
NSURL *url;
switch (i) {
case 0:
url = [NSURL URLWithString:kOverlyAttachedGirlfriendURLString];
break;
case 1:
url = [NSURL URLWithString:kSuccessKidURLString];
break;
case 2:
url = [NSURL URLWithString:kLotsOfFacesURLString];
break;
default:
break;
}
dispatch_group_enter(downloadGroup); // 3
Photo *photo = [[Photo alloc] initwithURL:url
withCompletionBlock:^(UIImage *image, NSError *_error) {
if (_error) {
error = _error;
}
dispatch_group_leave(downloadGroup); // 4
}];
[[PhotoManager sharedManager] addPhoto:photo];
}
dispatch_group_wait(downloadGroup, DISPATCH_TIME_FOREVER); // 5
dispatch_async(dispatch_get_main_queue(), ^{ // 6
if (completionBlock) { // 7
completionBlock(error);
}
});
});
}
Taking each numbered comment in turn, you’ll see the following:
1、Since you’re using the synchronous dispatch_group_wait which blocks the current thread, you use dispatch_async to place the entire method into a background queue to ensure you don’t block the main thread.
2、This creates a new dispatch group which behaves somewhat like a counter of the number of uncompleted tasks.
3、dispatch_group_enter manually notifies a group that a task has started. You must balance out the number of dispatch_group_enter calls with the number of dispatch_group_leave calls or else you’ll experience some weird crashes.
4、Here you manually notify the group that this work is done. Again, you’re balancing all group enters with an equal amount of group leaves.
5、dispatch_group_wait waits until either all of the tasks are complete or until the time expires. If the time expires before all events complete, the function will return a non-zero result. You could put this into a conditional block to check if the waiting period expired; however, in this case you specified for it to wait forever by supplying DISPATCH_TIME_FOREVER. This means, unsurprisingly, it’ll wait, forever! That’s fine, because the completion of the photos creation will always complete.
6、At this point, you are guaranteed that all image tasks have either completed or timed out. You then make a call back to the main queue to run your completion block. This will append work onto the main thread to be executed at some later time.
7、Finally, check if the completion block is nil, and if not, run the completion block.
六、Dispatch groups, take two
That’s all well and good, but it’s a bit clumsy to have to dispatch asynchronously onto another queue and then block using dispatch_group_wait. There’s another way…
- (void)downloadPhotosWithCompletionBlock:(BatchPhotoDownloadingCompletionBlock)completionBlock
{
// 1
__block NSError *error;
dispatch_group_t downloadGroup = dispatch_group_create();
for (NSInteger i = 0; i < 3; i++) {
NSURL *url;
switch (i) {
case 0:
url = [NSURL URLWithString:kOverlyAttachedGirlfriendURLString];
break;
case 1:
url = [NSURL URLWithString:kSuccessKidURLString];
break;
case 2:
url = [NSURL URLWithString:kLotsOfFacesURLString];
break;
default:
break;
}
dispatch_group_enter(downloadGroup); // 2
Photo *photo = [[Photo alloc] initwithURL:url
withCompletionBlock:^(UIImage *image, NSError *_error) {
if (_error) {
error = _error;
}
dispatch_group_leave(downloadGroup); // 3
}];
[[PhotoManager sharedManager] addPhoto:photo];
}
dispatch_group_notify(downloadGroup, dispatch_get_main_queue(), ^{ // 4
if (completionBlock) {
completionBlock(error);
}
});
}
Here’s how your new asynchronous method works:
1、In this new implementation you don’t need to surround the method in an async call since you’re not blocking the main thread.
2、This is the same enter method; there aren’t any changes here.
3、This is the same leave method; there aren’t any changes here either.
4、dispatch_group_notify serves as the asynchronous completion block. This code executes when there are no more items left in the dispatch group and it’s the completion block’s turn to run. You also specify on which queue to run your completion code, here, the main queue is the one you want.
参考: