iOS多線程GCD 研究

來源:互聯網
上載者:User

標籤:style   blog   http   io   os   ar   使用   java   for   

Grand Central Dispatch (GCD)是Apple開發的一個多核編程的解決方案。
dispatch queue分成以下三種:
1)運行在主線程的Main queue,通過dispatch_get_main_queue擷取。

Java代碼  
  1. /*! 
  2. * @function dispatch_get_main_queue 
  3. * @abstract 
  4. * Returns the default queue that is bound to the main thread. 
  5. * @discussion 
  6. * In order to invoke blocks submitted to the main queue, the application must 
  7. * call dispatch_main(), NSApplicationMain(), or use a CFRunLoop on the main 
  8. * thread. 
  9. * @result 
  10. * Returns the main queue. This queue is created automatically on behalf of 
  11. * the main thread before main() is called. 
  12. */  
  13. __OSX_AVAILABLE_STARTING(__MAC_10_6,__IPHONE_4_0)  
  14. DISPATCH_EXPORT struct dispatch_queue_s _dispatch_main_q;  
  15. #define dispatch_get_main_queue() \  
  16. DISPATCH_GLOBAL_OBJECT(dispatch_queue_t, _dispatch_main_q)  
/*!* @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)

可以看出,dispatch_get_main_queue也是一種dispatch_queue_t。
2)並行隊列global dispatch queue,通過dispatch_get_global_queue擷取,由系統建立三個不同優先順序的dispatch queue。並行隊列的執行順序與其排入佇列的順序相同。
3)串列隊列serial queues一般用於按順序同步訪問,可建立任意數量的串列隊列,各個串列隊列之間是並發的。
當想要任務按照某一個特定的順序執行時,串列隊列是很有用的。串列隊列在同一個時間只執行一個任務。我們可以使用串列隊列代替鎖去保護共用的資料。和鎖不同,一個串列隊列可以保證任務在一個可預知的順序下執行。
serial queues通過dispatch_queue_create建立,可以使用函數dispatch_retain和dispatch_release去增加或者減少引用計數。
GCD的用法:

Java代碼  
  1. //  後台執行:  
  2.  dispatch_async(dispatch_get_global_queue(0, 0), ^{  
  3.       // something  
  4.  });  
  5.   
  6.  // 主線程執行:  
  7.  dispatch_async(dispatch_get_main_queue(), ^{  
  8.       // something  
  9.  });  
  10.   
  11.  // 一次性執行:  
  12.  static dispatch_once_t onceToken;  
  13.  dispatch_once(&onceToken, ^{  
  14.      // code to be executed once  
  15.  });  
  16.   
  17.  // 延遲2秒執行:  
  18.  double delayInSeconds = 2.0;  
  19.  dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);  
  20.  dispatch_after(popTime, dispatch_get_main_queue(), ^(void){  
  21.      // code to be executed on the main queue after delay  
  22.  });  
  23.   
  24.  // 自訂dispatch_queue_t  
  25.  dispatch_queue_t urls_queue = dispatch_queue_create("blog.devtang.com", NULL);  
  26.  dispatch_async(urls_queue, ^{    
  27.    // your code   
  28.  });  
  29.  dispatch_release(urls_queue);  
  30.   
  31.  // 合并匯總結果  
  32.  dispatch_group_t group = dispatch_group_create();  
  33.  dispatch_group_async(group, dispatch_get_global_queue(0,0), ^{  
  34.       // 並存執行的線程一  
  35.  });  
  36.  dispatch_group_async(group, dispatch_get_global_queue(0,0), ^{  
  37.       // 並存執行的線程二  
  38.  });  
  39.  dispatch_group_notify(group, dispatch_get_global_queue(0,0), ^{  
  40.       // 匯總結果  
  41.  });  
//  後台執行: dispatch_async(dispatch_get_global_queue(0, 0), ^{      // something }); // 主線程執行: dispatch_async(dispatch_get_main_queue(), ^{      // something }); // 一次性執行: static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{     // code to be executed once }); // 延遲2秒執行: 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), ^{      // 並存執行的線程一 }); dispatch_group_async(group, dispatch_get_global_queue(0,0), ^{      // 並存執行的線程二 }); dispatch_group_notify(group, dispatch_get_global_queue(0,0), ^{      // 匯總結果 });

一個應用GCD的例子:

Java代碼  
  1. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{  
  2.         NSURL * url = [NSURL URLWithString:@"http://www.baidu.com"];  
  3.         NSError * error;  
  4.         NSString * data = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];  
  5.         if (data != nil) {  
  6.             dispatch_async(dispatch_get_main_queue(), ^{  
  7.                 NSLog(@"call back, the data is: %@", data);  
  8.             });  
  9.         } else {  
  10.             NSLog(@"error when download:%@", error);  
  11.         }  
  12.     });  
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);        }    });

GCD的另一個用處是可以讓程式在後台較長久的運行。
在沒有使用GCD時,當app被按home鍵退出後,app僅有最多5秒鐘的時候做一些儲存或清理資源的工作。但是在使用GCD後,app最多有10分鐘的時間在後台長久運行。這個時間可以用來做清理本機快取,發送統計資料等工作。
讓程式在後台長久啟動並執行範例程式碼如下:

Java代碼  
  1. // AppDelegate.h檔案  
  2. @property (assign, nonatomic) UIBackgroundTaskIdentifier backgroundUpdateTask;  
  3.   
  4. // AppDelegate.m檔案  
  5. - (void)applicationDidEnterBackground:(UIApplication *)application  
  6. {  
  7.     [self beingBackgroundUpdateTask];  
  8.     // 在這裡加上你需要長久啟動並執行代碼  
  9.     [self endBackgroundUpdateTask];  
  10. }  
  11.   
  12. - (void)beingBackgroundUpdateTask  
  13. {  
  14.     self.backgroundUpdateTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{  
  15.         [self endBackgroundUpdateTask];  
  16.     }];  
  17. }  
  18.   
  19. - (void)endBackgroundUpdateTask  
  20. {  
  21.     [[UIApplication sharedApplication] endBackgroundTask: self.backgroundUpdateTask];  
  22.     self.backgroundUpdateTask = UIBackgroundTaskInvalid;  
  23. }  

iOS多線程GCD 研究

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.