GCD related stuff

From:http://www.cnblogs.com/pure/archive/2013/03/31/2977420.html

Grand Central Dispatch (GCD) is a multi-core programming solution developed by Apple.

The dispatch queue is divided into the following three types:

1) The Main queue running on the main thread is obtained through dispatch_get_main_queue.

copy code
/*!
* @function dispatch_get_main_queue
*
* @abstract
* Returns the default queue that is bound to the main thread.
*
* @discussion
* In order to invoke blocks submitted to the main queue, the application must
* call dispatch_main(), NSApplicationMain(), or use a CFRunLoop on the main
* thread.
*
* @result
* Returns the main queue. This queue is created automatically on behalf of
* the main thread before main() is called.
*/
__OSX_AVAILABLE_STARTING(__MAC_10_6,__IPHONE_4_0)
DISPATCH_EXPORT struct dispatch_queue_s _dispatch_main_q;
#define dispatch_get_main_queue() \
DISPATCH_GLOBAL_OBJECT(dispatch_queue_t, _dispatch_main_q)
copy code

It can be seen that dispatch_get_main_queue is also a dispatch_queue_t.

2) Parallel queue global dispatch queue, obtained through dispatch_get_global_queue, and the system creates three dispatch queues with different priorities. Parallel queues are executed in the same order as they were added to the queue.

3) Serial queues serial queues are generally used for synchronous access in order, and any number of serial queues can be created, and each serial queue is concurrent.

Serial queues are useful when you want tasks to be executed in a certain order. A serial queue executes only one task at a time. We can use serial queues instead of locks to protect shared data. Unlike locks, a serial queue guarantees that tasks are executed in a predictable order.

Serial queues are created by dispatch_queue_create, and the functions dispatch_retain and dispatch_release can be used to increase or decrease the reference count.

Usage of GCD :

copy code
 //   Background execution: 
 dispatch_async(dispatch_get_global_queue( 0 , 0 ), ^ {
       // something 
}); 

 // Main thread execution: 
 dispatch_async(dispatch_get_main_queue(), ^ {
       // something 
}); 

 // One-time execution: 
 static dispatch_once_t onceToken; 
 dispatch_once( &onceT oken, ^ {
      // code to be executed once 
}); 

 // Delay execution by 2 seconds: 
 double delayInSeconds = 2.0 ; 
 dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
 dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
     // code to be executed on the main queue after delay
 });

 // 自定义dispatch_queue_t
 dispatch_queue_t urls_queue = dispatch_queue_create("blog.devtang.com", NULL);
 dispatch_async(urls_queue, ^{  
   // your code 
 });
 dispatch_release(urls_queue);

 // 合并汇总结果
 dispatch_group_t group = dispatch_group_create();
 dispatch_group_async(group, dispatch_get_global_queue(0,0), ^{
       // Thread 1 executed in parallel 
}); 
 dispatch_group_async(group, dispatch_get_global_queue( 0 , 0 ), ^ {
       // Thread 2 executed in parallel 
}); 
 dispatch_group_notify(group, dispatch_get_global_queue( 0 , 0 ), ^ {
       // Summary results 
 });
copy code

An example applying GCD:

copy code
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL * url = [NSURL URLWithString:@"http://www.baidu.com"];
        NSError * error;
        NSString * data = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
        if (data != nil) {
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"call back, the data is: %@", data);
            });
        } else {
            NSLog(@"error when download:%@", error);
        }
    });
copy code

GCD的另一个用处是可以让程序在后台较长久的运行。

在没有使用GCD时,当app被按home键退出后,app仅有最多5秒钟的时候做一些保存或清理资源的工作。但是在使用GCD后,app最多有10分钟的时间在后台长久运行。这个时间可以用来做清理本地缓存,发送统计数据等工作。

让程序在后台长久运行的示例代码如下:

copy code
// AppDelegate.h文件
@property (assign, nonatomic) UIBackgroundTaskIdentifier backgroundUpdateTask;

// AppDelegate.m文件
- (void)applicationDidEnterBackground:(UIApplication *)application
{
    [self beingBackgroundUpdateTask];
    // 在这里加上你需要长久运行的代码
    [self endBackgroundUpdateTask];
}

- (void)beingBackgroundUpdateTask
{
    self.backgroundUpdateTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        [self endBackgroundUpdateTask];
    }];
}

- (void)endBackgroundUpdateTask
{
    [[UIApplication sharedApplication] endBackgroundTask: self.backgroundUpdateTask];
    self.backgroundUpdateTask = UIBackgroundTaskInvalid;
}
copy code

 

Organized from: Using GCD    to explain the concurrent Dispatch Queues of IOS development applications

Guess you like

Origin blog.csdn.net/sirodeng/article/details/50612564
gcd