1.GCD(Grand Centrol Dispath)
并行:宏觀和微觀都是兩個人再拿著兩把鐵鍬在挖坑,1小時挖兩個大坑
并發(fā):宏觀上是感覺他們都在挖坑,微觀是他們是在使用1把鐵鍬挖坑,1小時后他們挖了兩個小坑。
總結(jié):就單個cpu來講,大部份進程是并發(fā)進行的,就是1把鐵鍬,你1下我1下,只是間隔時間較短,用戶感覺不到而已。
利用:
GCD包括:
(1)實際使用中( 而系統(tǒng)默許就有1個串行隊列main_queue和并行隊列g(shù)lobal_queue:
//dispatch_get_global_queue(0, 0)第1個0是優(yōu)先級,第2個保存字段
dispatch_async(dispatch_get_global_queue(0, 0), ^{
//在這里可以是數(shù)據(jù)要求
NSString* result = [self requestData:parameter];
//在這里返回主線程刷新數(shù)據(jù)
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)也能夠自己創(chuàng)建(我是不怎樣用)
串行隊列,顧名思義,1串嘛,那就得并發(fā)履行嘍
//自己創(chuàng)建serial queue
dispatch_queue_t queue = dispatch_queue_create("com.class15.queue", DISPATCH_QUEUE_SERIAL);
//異步履行線程
dispatch_async(queue, ^{
NSLog(@"任務(wù)1:%@ %d", [NSThread currentThread],[NSThread currentThread].isMainThread);
});
并行隊列通過dispatch_get_global_queue獲得,由系統(tǒng)創(chuàng)建3個不同優(yōu)先級的dispatch queue
//創(chuàng)建自己的隊列
dispatch_queue_t queue = dispatch_queue_create("com.class15.comcrrentQueue", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue, ^{
NSLog(@"任務(wù)1:%@ %d", [NSThread currentThread],[NSThread currentThread].isMainThread);
});
上一篇 優(yōu)酷網(wǎng)網(wǎng)絡(luò)流播放地址url的獲取新方法
下一篇 [置頂] 通過tcpdump抓取 指定 ip 端口 的網(wǎng)絡(luò)數(shù)據(jù),并通過wireshark分析網(wǎng)絡(luò)數(shù)據(jù),很實用