詳解iOS多線程GCD問題
在iOS所有實現(xiàn)多線程的方案中,GCD應該是最有魅力的,因為GCD本身是蘋果公司為多核的并行運算提出的解決方案。GCD在工作時會自動利用更多的處理器核心,以充分利用更強大的機器。GCD是Grand Central Dispatch的簡稱,它是基于C語言的。如果使用GCD,完全由系統(tǒng)管理線程,我們不需要編寫線程代碼。只需定義想要執(zhí)行的任務,然后添加到適當?shù)恼{度隊列(dispatch queue)。GCD會負責創(chuàng)建線程和調度你的任務,系統(tǒng)直接提供線程管理
dispatch queue分成以下三種:
1)運行在主線程的Main queue,通過dispatch_get_main_queue獲取。
/*! * @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獲取,由系統(tǒng)創(chuàng)建三個不同優(yōu)先級的dispatch queue。并行隊列的執(zhí)行順序與其加入隊列的順序相同。
3)串行隊列serial queues一般用于按順序同步訪問,可創(chuàng)建任意數(shù)量的串行隊列,各個串行隊列之間是并發(fā)的。
當想要任務按照某一個特定的順序執(zhí)行時,串行隊列是很有用的。串行隊列在同一個時間只執(zhí)行一個任務。我們可以使用串行隊列代替鎖去保護共享的數(shù)據(jù)。和鎖不同,一個串行隊列可以保證任務在一個可預知的順序下執(zhí)行。
serial queues通過dispatch_queue_create創(chuàng)建,可以使用函數(shù)dispatch_retain和dispatch_release去增加或者減少引用計數(shù)。
GCD的用法:
// 后臺執(zhí)行:
dispatch_async(dispatch_get_global_queue(0, 0), ^{
// something
});
// 主線程執(zhí)行:
dispatch_async(dispatch_get_main_queue(), ^{
// something
});
// 一次性執(zhí)行:
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
// code to be executed once
});
// 延遲2秒執(zhí)行:
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), ^{
// 并行執(zhí)行的線程一
});
dispatch_group_async(group, dispatch_get_global_queue(0,0), ^{
// 并行執(zhí)行的線程二
});
dispatch_group_notify(group, dispatch_get_global_queue(0,0), ^{
// 匯總結果
});
一個應用GCD的例子:
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分鐘的時間在后臺長久運行。這個時間可以用來做清理本地緩存,發(fā)送統(tǒng)計數(shù)據(jù)等工作。
讓程序在后臺長久運行的示例代碼如下:
// 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;
}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
IOS 下獲取 rootviewcontroller 的版本不同的問題解決辦法
這篇文章主要介紹了IOS 下獲取 rootviewcontroller 的版本不同的問題解決辦法的相關資料,希望通過本文能幫助到大家,讓大家遇到這種問題可以解決,需要的朋友可以參考下2017-10-10
IOS 中NSUserDefaults讀取和寫入自定義對象的實現(xiàn)方法
這篇文章主要介紹了IOS 中NSUserDefaults讀取和寫入自定義對象的實現(xiàn)方法的相關資料,希望通過本文大家能夠理解掌握這部分內容,需要的朋友可以參考下2017-09-09
簡介Objective-C解析XML與JSON數(shù)據(jù)格式的方法
這篇文章主要介紹了Objective-C解析XML與JSON數(shù)據(jù)格式的方法,文中解析JSON包括拼接JSON字符串用到了SBJson這個解析器,需要的朋友可以參考下2016-01-01
IOS開發(fā)代碼分享之用nstimer實現(xiàn)倒計時功能
在制作IOS項目中,我們經常要用到倒計時功能,今天就分享下使用nstimer實現(xiàn)的倒計時功能的代碼,希望對大家能有所幫助2014-09-09

