標籤:gcd ios 線程 多線程 並發
1.GCD(Grand Centrol Dispath)
並行:宏觀以及微觀都是兩個人再拿著兩把鐵鍬在挖坑,一小時挖兩個大坑
並發:宏觀上是感覺他們都在挖坑,微觀是他們是在使用一把鐵鍬挖坑,一小時後他們挖了兩個小坑。
總結:就單個cpu來說,大部分進程是並發進行的,就是一把鐵鍬,你一下我一下,只是間隔時間較短,使用者感覺不到而已。
應用:
GCD包括:
(1)實際使用中
//dispatch_get_global_queue(0, 0)第一個0是優先順序,第二個保留欄位
dispatch_async(dispatch_get_global_queue(0, 0), ^{
//在這裡可以是資料請求
NSString* result = [self requestData:parameter];
//在這裡返回主線程重新整理資料
dispatch_async(dispatch_get_main_queue(), ^{
[mainTableView reloadData];
});
});
舉例說明:
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);
}
});
(2)也可以自己建立(我是不怎麼用)
串列隊列,顧名思義,一串嘛,那就得並發執行嘍
//自己建立serial queue
dispatch_queue_t queue = dispatch_queue_create("com.class15.queue", DISPATCH_QUEUE_SERIAL);
//非同步執行線程
dispatch_async(queue, ^{
NSLog(@"任務1:%@ %d", [NSThread currentThread],[NSThread currentThread].isMainThread);
});
並行隊列通過dispatch_get_global_queue擷取,由系統建立三個不同優先順序的dispatch queue
//建立自己的隊列
dispatch_queue_t queue = dispatch_queue_create("com.class15.comcrrentQueue", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue, ^{
NSLog(@"任務1:%@ %d", [NSThread currentThread],[NSThread currentThread].isMainThread);
});
iOS 開發之多線程之GCD