一重父、多線程的基本概念
進程:可以理解成一個運行中的應用程序忽匈,是系統(tǒng)進行資源分配和調度的基本單位,是操作系統(tǒng)結構的基礎郭厌,主要管理資源沪曙。
線程:是進程的基本執(zhí)行單元萎羔,一個進程對應多個線程贾陷。
主線程:處理UI,所有更新UI的操作都必須在主線程上執(zhí)行巷懈。不要把耗時操作放在主線程慌洪,會卡界面冈爹。更新UI的操作必須要放到主線程中執(zhí)行
多線程:在同一時刻,一個CPU只能處理1條線程恳谎,但CPU可以在多條線程之間快速的切換因痛,只要切換的足夠快岸更,就造成了多線程一同執(zhí)行的假象怎炊。
進程和線程的關系:線程就像火車的一節(jié)車廂用僧,進程則是火車责循。車廂(線程)離開火車(進程)是無法跑動的攀操,而火車(進程)至少有一節(jié)車廂(主線程)速和。多線程可以看做多個車廂,它的出現(xiàn)是為了提高效率排惨。
多線程是通過提高資源使用率來提高系統(tǒng)總體的效率碰凶。
- NSThread
NSThread是基于線程使用欲低,輕量級的多線程編程方法(相對GCD和NSOperation),一個NSThread對象代表一個線程砾莱,需要手動管理線程的生命周期腊瑟,處理線程同步等問題。
NSThread的創(chuàng)建有以下三種方法:
/** 方法一膘格,需要start */
NSThread *thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(doSomething1:) object:@"NSThread1"];
// 線程加入線程池等待CPU調度闯袒,時間很快游岳,幾乎是立刻執(zhí)行
[thread1 start];
/** 方法二胚迫,創(chuàng)建好之后自動啟動 */
[NSThread detachNewThreadSelector:@selector(doSomething2:) toTarget:self withObject:@"NSThread2"];
/** 方法三唾那,隱式創(chuàng)建,直接啟動 */
[self performSelectorInBackground:@selector(doSomething3:) withObject:@"NSThread3"];
2.GCD
全稱Grand Center Dispatch ,是 Apple 開發(fā)的一個多核編程的解決方法河哑,簡單易用龟虎,效率高鲤妥,速度快,基于C語言底扳,更底層更高效衷模,并且不是Cocoa框架的一部分菇爪,自動管理線程生命周期(創(chuàng)建線程凳宙、調度任務、銷毀線程)
GCD提供了三種隊列
1)The main queue(主線程串行隊列): 與主線程功能相同届囚,提交至Main queue的任務會在主線程中執(zhí)行意系,Main queue 可以通過dispatch_get_main_queue()來獲取饺汹。
2)Global queue(全局并發(fā)隊列): 全局并發(fā)隊列由整個進程共享兜辞,有高、中(默認)凶硅、低足绅、后臺四個優(yōu)先級別。Global queue 可以通過調用dispatch_get_global_queue函數來獲却馕邸(可以設置優(yōu)先級)
3) Custom queue (自定義隊列): 可以為串行厕怜,也可以為并發(fā)蕾总。
Custom queue 可以通過dispatch_queue_create()來獲取生百。
主隊列:
回到主線程操作
//GCD
dispatch_async(dispatch_get_main_queue(), ^{
//回到主線程蚀浆,今進行UI刷新以及其它對界面的操作
});
//1.NSThread
[self performSelectorOnMainThread:@selector(test) withObject:nil waitUntilDone:NO];
//NSOperationQueue
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
// UI更新代碼
self.alert.text = @"Thanks!";
}];
自定義隊列:
串行:
dispatch_queue_t serialQueue = dispatch_queue_create("test", DISPATCH_QUEUE_SERIAL);
NSLog(@"當前任務1");
dispatch_async(serialQueue, ^{
NSLog(@"當前任務2");
sleep(2);
});
dispatch_async(serialQueue, ^{
NSLog(@"當前任務3");
});
執(zhí)行結果為:
說明串行隊列只開啟了一個線程市俊,在該線程中順序執(zhí)行。
自定義并發(fā)隊列:
dispatch_queue_t conCurrentQueue = dispatch_queue_create("TestCon", DISPATCH_QUEUE_CONCURRENT);
NSLog(@"1");
NSLog(@"one:%@",[NSThread currentThread]);
dispatch_async(conCurrentQueue, ^{
NSLog(@"2");
NSLog(@"two:%@",[NSThread currentThread]);
});
dispatch_async(conCurrentQueue, ^{
NSLog(@"3");
NSLog(@"three:%@",[NSThread currentThread]);
});
NSLog(@"4");
執(zhí)行結果為:
說明串行隊列開啟了多個線程去執(zhí)行,執(zhí)行的順序不定(誰執(zhí)行的快誰先結束)
3 全局并發(fā)隊列
dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
或
dispatch_queue_t globalQueue = dispatch_get_global_queue(0, 0);
和自定義的并發(fā)隊列用法一樣伺帘,只不過它是由系統(tǒng)管理伪嫁,不需要我們去手動釋放
4.工作中經常用到的GCD
1)生成單例
#import "SingleIntanceTest.h"
//一定要是定義全局靜態(tài)的 因為全局靜態(tài)變量的作用范圍是整個程序的生命周期
static SingleIntanceTest *__singleInstacess = nil;
@implementation SingleIntanceTest
+ (instancetype)shareInstace
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
__singleInstacess = [[SingleIntanceTest alloc] init];
});
return __singleInstacess;
}
@end
2)組隊列dispatch_group_t 所有任務執(zhí)行完畢后的統(tǒng)一回調
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_t group = dispatch_group_create();
//里面的代碼需要時順序執(zhí)行 不然沒有效果
dispatch_group_async(group, queue, ^{
NSLog(@"one");
});
dispatch_group_async(group, queue, ^{
NSLog(@"two");
});
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"執(zhí)行完畢");
});
3)信號量 異步變同步
簡單來講 信號量為0則阻塞線程张咳,大于0則不會阻塞脚猾。則我們通過改變信號量的值啄枕,來控制是否阻塞線程频祝,從而達到線程同步。
在GCD中有三個函數是semaphore的操作沽一,
分別是:
dispatch_semaphore_create 創(chuàng)建一個semaphore
dispatch_semaphore_signal 發(fā)送一個信號
dispatch_semaphore_wait 等待信號
簡單的介紹一下這三個函數铣缠,第一個函數有一個整形的參數昆禽,我們可以理解為信號的總量醉鳖,dispatch_semaphore_signal是發(fā)送一個信號盗棵,自然會讓信號總量加1,dispatch_semaphore_wait等待信號喷屋,當信號總量少于0的時候就會一直等待屯曹,否則就可以正常的執(zhí)行惊畏,并讓信號總量-1陕截,根據這樣的原理,我們便可以快速的創(chuàng)建一個并發(fā)控制來同步任務和有限資源訪問控制社搅。
在開發(fā)中我們需要等待某個網絡回調完之后才執(zhí)行后面的操作形葬,應用如下:
//又拍云上傳視頻 用信號量將異步轉同步
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
NSString *saveKey = [NSString stringWithFormat:@"%@%@.mp4",_pingUploadUrlString, [self return16LetterAndNumber]];
[[UPYUNConfig sharedInstance] uploadFilePath:_filePath saveKey:saveKey success:^(NSHTTPURLResponse *response, NSDictionary *responseBody)
{
_isVideoUploadSuccess = YES;
NSString *strsss = [UPLOAD_FILEURL stringByAppendingString:responseBody[@"url"]];
NSLog(@"視頻地址是:%@",strsss);
dispatch_semaphore_signal(sema);
} failure:^(NSError *error, NSHTTPURLResponse *response, NSDictionary *responseBody) {
_isVideoUploadSuccess = NO;
dispatch_semaphore_signal(sema);
} progress:^(int64_t completedBytesCount, int64_t totalBytesCount) {
}];
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
4)定時器
延時執(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){
//執(zhí)行事件
});
重復執(zhí)行:
NSTimeInterval period = 1.0; //設置時間間隔
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), period * NSEC_PER_SEC, 0); //每秒執(zhí)行
dispatch_source_set_event_handler(_timer, ^{
//在這里執(zhí)行事件
});
dispatch_resume(_timer);
5)dispatch_barrier_async 柵欄函數
dispatch_barrier_async函數的作用與barrier的意思相同,在進程管理中起到一個柵欄的作用,它等待所有位于barrier函數之前的操作執(zhí)行完畢后執(zhí)行,并且在barrier函數執(zhí)行之后,barrier函數之后的操作才會得到執(zhí)行,該函數需要同dispatch_queue_create函數生成的concurrent Dispatch Queue隊列一起使用,不能使用系統(tǒng)自帶的全局并發(fā)隊列猖腕。
//同dispatch_queue_create函數生成的concurrent Dispatch Queue隊列一起使用
dispatch_queue_t queue = dispatch_queue_create("barrierTest", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue, ^{
NSLog(@"----1-----%@", [NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"----2-----%@", [NSThread currentThread]);
});
dispatch_barrier_async(queue, ^{
NSLog(@"----barrier-----%@", [NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"----3-----%@", [NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"----4-----%@", [NSThread currentThread]);
});
3.NSOperation
NSOperation倘感、NSOperationQueue 是蘋果提供給我們的一套多線程解決方案老玛。實際上 NSOperation、NSOperationQueue 是基于 GCD 更高一層的封裝麸粮,完全面向對象豹休。但是比 GCD 更簡單易用桨吊、代碼可讀性也更高视乐。
NSOperation是一個抽象類,實現(xiàn)NSOperation子類的方式有3種:
NSInvocationOperation:較少使用留美;
NSBlockOperation:最常使用谎砾;
自定義子類繼承NSOperation捧颅,實現(xiàn)內部相應的方法:很少使用碉哑。
1)使用NSInvocationOperation
// 創(chuàng)建NSInvocationOperation
NSInvocationOperation *invocationOperation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(invocationOperation) object:nil];
// 開始執(zhí)行操作
[invocationOperation start];
這樣執(zhí)行是沒有開啟分線程,直接在當前線程中執(zhí)行
2)NSBlockOperation
// 把任務放到block中
NSBlockOperation *blockOperation = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"NSBlockOperation包含的任務妆毕,沒有加入隊列========%@", [NSThread currentThread]);
}];
[blockOperation start];
addExecutionBlock實現(xiàn)多線程:
NSBlockOperation *blockOperation = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"NSBlockOperation運用addExecutionBlock========%@", [NSThread currentThread]);
}];
[blockOperation addExecutionBlock:^{
NSLog(@"addExecutionBlock方法添加任務1========%@", [NSThread currentThread]);
}];
[blockOperation addExecutionBlock:^{
NSLog(@"addExecutionBlock方法添加任務2========%@", [NSThread currentThread]);
}];
[blockOperation addExecutionBlock:^{
NSLog(@"addExecutionBlock方法添加任務3========%@", [NSThread currentThread]);
}];
[blockOperation start];
3)自定義NSOperation
如果使用子類 NSInvocationOperation、NSBlockOperation 不能滿足日常需求薪前,我們可以使用自定義繼承自 NSOperation 的子類。可以通過重寫 main 或者 start 方法 來定義自己的 NSOperation 對象例诀。
#import <Foundation/Foundation.h>
@interface AnimationNSoperation : NSOperation
@end
#import "AnimationNSoperation.h"
@implementation AnimationNSoperation
- (void)main
{
for (int i = 0; i<5; i++)
{
NSLog(@"測試啊");
}
}
@end
AnimationNSoperation *animation = [[AnimationNSoperation alloc] init];
[animation start];
4)NSOperationQueue 控制串行執(zhí)行繁涂、并發(fā)執(zhí)行
最大并發(fā)操作數:maxConcurrentOperationCount
maxConcurrentOperationCount 默認情況下為-1,表示不進行限制二驰,可進行并發(fā)執(zhí)行扔罪。
maxConcurrentOperationCount 為1時,隊列為串行隊列桶雀。只能串行執(zhí)行矿酵。
maxConcurrentOperationCount 大于1時,隊列為并發(fā)隊列矗积。操作并發(fā)執(zhí)行全肮,當然這個值不應超過系統(tǒng)限制,即使自己設置一個很大的值棘捣,系統(tǒng)也會自動調整為 min{自己設定的值辜腺,系統(tǒng)設定的默認最大值}乍恐。
// 1.創(chuàng)建隊列
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
// 2.設置最大并發(fā)操作數
queue.maxConcurrentOperationCount = 1; // 串行隊列
// queue.maxConcurrentOperationCount = 2; // 并發(fā)隊列
// queue.maxConcurrentOperationCount = 8; // 并發(fā)隊列
// 3.添加操作
[queue addOperationWithBlock:^{
for (int i = 0; i < 2; i++) {
[NSThread sleepForTimeInterval:2]; // 模擬耗時操作
NSLog(@"1---%@", [NSThread currentThread]); // 打印當前線程
}
}];
[queue addOperationWithBlock:^{
for (int i = 0; i < 2; i++) {
[NSThread sleepForTimeInterval:2]; // 模擬耗時操作
NSLog(@"2---%@", [NSThread currentThread]); // 打印當前線程
}
}];
[queue addOperationWithBlock:^{
for (int i = 0; i < 2; i++) {
[NSThread sleepForTimeInterval:2]; // 模擬耗時操作
NSLog(@"3---%@", [NSThread currentThread]); // 打印當前線程
}
}];
[queue addOperationWithBlock:^{
for (int i = 0; i < 2; i++) {
[NSThread sleepForTimeInterval:2]; // 模擬耗時操作
NSLog(@"4---%@", [NSThread currentThread]); // 打印當前線程
}
}];
5)NSOperation 操作依賴
NSOperation评疗、NSOperationQueue 能添加操作之間的依賴關系。通過操作依賴茵烈,我們可以很方便的控制操作之間的執(zhí)行先后順序百匆。NSOperation 提供了3個接口供我們管理和查看依賴
- (void)addDependency:(NSOperation *)op;
添加依賴,使當前操作依賴于操作 op 的完成呜投。
- (void)removeDependency:(NSOperation *)op;
移除依賴胧华,取消當前操作對操作 op 的依賴。
@property (readonly, copy) NSArray<NSOperation *> *dependencies;
在當前操作開始執(zhí)行之前完成執(zhí)行的所有操作對象數組宙彪。
我們經常用到的還是添加依賴操作矩动。
// 1.創(chuàng)建隊列
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
// 2.創(chuàng)建操作
NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{
for (int i = 0; i < 2; i++)
{
[NSThread sleepForTimeInterval:2]; // 模擬耗時操作
NSLog(@"1---%@", [NSThread currentThread]); // 打印當前線程
}
}];
NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{
for (int i = 0; i < 2; i++)
{
[NSThread sleepForTimeInterval:2]; // 模擬耗時操作
NSLog(@"2---%@", [NSThread currentThread]); // 打印當前線程
}
}];
// 3.添加依賴
[op2 addDependency:op1]; // 讓op2 依賴于 op1,則先執(zhí)行op1释漆,在執(zhí)行op2
// 4.添加操作到隊列中
[queue addOperation:op1];
[queue addOperation:op2];