1.NSThread
每個NSThread對象對應(yīng)一個線程,真正最原始的線程登颓。
1)優(yōu)點:NSThread 輕量級最低月帝,相對簡單躏惋。
2)缺點:手動管理所有的線程活動,如生命周期嚷辅、線程同步簿姨、睡眠等。
2.NSOperation
自帶線程管理的抽象類簸搞。
1)優(yōu)點:自帶線程周期管理扁位,操作上可更注重自己邏輯。
2)缺點:面向?qū)ο蟮某橄箢惓每。荒軐崿F(xiàn)它或者使用它定義好的兩個子類:NSInvocationOperation 和 NSBlockOperation域仇。
3.GCD
Grand Central Dispatch (GCD)是Apple開發(fā)的一個多核編程的解決方法。
1)優(yōu)點:最高效寺擂,避開并發(fā)陷阱暇务。
2)缺點:基于C實現(xiàn)。
4.選擇小結(jié)
1)簡單而安全的選擇NSOperation實現(xiàn)多線程即可怔软。
2)處理大量并發(fā)數(shù)據(jù)垦细,又追求性能效率的選擇GCD。
3)在頻繁使用多線程的程序中一般不建議使用NSThread
1挡逼、自定義串行隊列
// 串行隊列 SERIAL
dispatch_queue_t queue = dispatch_queue_create("SERIAL", DISPATCH_QUEUE_SERIAL);
// 防止循環(huán)引用 使用 __weak 修飾
__weak typeof(self)weakSelf = self;
// 異步任務(wù) 分線程中執(zhí)行 不會阻塞主線程
dispatch_async(queue, ^{
[weakSelf eat];
});
// 同步任務(wù) 主線程中執(zhí)行 會阻塞當(dāng)前線程
dispatch_sync(queue, ^{
[weakSelf eat];
});
2括改、自定義并行隊列
// 并行隊列 CONCURRENT
dispatch_queue_t queue2 = dispatch_queue_create("CONCURRENT", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue2, ^{
[weakSelf eat];
});
dispatch_sync(queue2, ^{
[weakSelf eat];
});
3、獲取系統(tǒng)的4個并行隊列
dispatch_queue_t queue4 = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue4, ^{
[weakSelf eat];
});
4家坎、子線程中執(zhí)行完之后嘱能,回到主線程
dispatch_async(dispatch_get_main_queue(), ^{
// 更新UI
});
5、所有任務(wù)執(zhí)行完成后回調(diào)(執(zhí)行任務(wù)為同步請求)
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group乘盖,queue2焰檩,^{執(zhí)行任務(wù)A});
dispatch_group_async(group,queue2订框,^{執(zhí)行任務(wù)B});
dispatch_group_async(group析苫,queue2,^{執(zhí)行任務(wù)C});
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"queue2的所有任務(wù)都執(zhí)行完了");
});
6、網(wǎng)絡(luò)異步請求--(利用group)所有任務(wù)執(zhí)行完成后回調(diào)
@property (nonatomic, strong, nullable) dispatch_group_t serviceGroup;
[SVProgressHUD showModalLoading];
//(重復(fù)調(diào)用會出現(xiàn)dispatch_group相關(guān)的巨坑,因此要判斷group是否為空)
if (self.serviceGroup == nil) {
dispatch_group_t group = dispatch_group_create();
self.serviceGroup = group;
}
[self loadData];//加載數(shù)據(jù)
dispatch_group_notify(self.serviceGroup, dispatch_get_main_queue(), ^{
[SVProgressHUD dismissModalLoadingView];
});
- (void)loadData {
WS(weakSelf);
dispatch_group_enter(self.serviceGroup);
NSMutableDictionary *parameter = [NSMutableDictionary dictionary];
parameter[@""] = @"";
[[NetWorkingManager shareManager] GET:@"" parameters:parameter progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
dispatch_group_leave(weakSelf.serviceGroup);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
}];
}
7衩侥、網(wǎng)絡(luò)異步請求--(利用信號量)按順序執(zhí)行
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self loadDataWithSemaphore:semaphore];
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
[self loadDataWithSemaphore:semaphore];
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
[self loadData3];
});
- (void)loadDataWithSemaphore:(dispatch_semaphore_t)semaphore {
WS(weakSelf);
NSMutableDictionary *parameter = [NSMutableDictionary dictionary];
parameter[@""] = @"";
[[NetWorkingManager shareManager] GET:@"" parameters:parameter progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
dispatch_semaphore_signal(semaphore);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
}];
}
//信號量-->dispatch_semaphore_create
http://www.reibang.com/p/73470d7de082
8国旷、GCD柵欄函數(shù)
這里我們用到柵欄函數(shù)dispatch_barrier_(a)sync,(也可以用隊列組),我們要注意的是不能使用全局并發(fā)隊列(系統(tǒng)提供給我們的)否則會散失柵欄函數(shù)的意義
針對dispatch_barrier_sync 如果你傳入的是串行或全局并發(fā)隊列 則它的作用和 dispatch_sync 一樣; 如果是 dispatch_barrier_async 則它的作用和 dispatch_async一樣
區(qū)別:先看官方文檔
dispatch_barrier_sync: Submits a barrier block object for execution and waits until that block completes.(提交一個柵欄函數(shù)在執(zhí)行中,它會等待柵欄函數(shù)執(zhí)行完)
我的理解:阻塞 queue茫死,不同的是 這個方法還會 阻塞當(dāng)前線程跪但。
dispatch_barrier_async: Submits a barrier block for asynchronous execution and returns immediately.(提交一個柵欄函數(shù)在異步執(zhí)行中,它會立馬返回)
我的理解:這個方法會阻塞這個 queue(注意是阻塞 queue ,而不是阻塞當(dāng)前線程)
1.先來看看dispatch_barrier_sync
- (void)test {
//創(chuàng)建一個自定義并發(fā)隊列
NSLog(@"start");
dispatch_queue_t queue = dispatch_queue_create("CONCURRENT", DISPATCH_QUEUE_CONCURRENT);
//異步函數(shù) 無序執(zhí)行
dispatch_async(queue, ^{
NSLog(@"%@ -- 1", [NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"%@ -- 2", [NSThread currentThread]);
});
dispatch_barrier_sync(queue, ^{
NSLog(@"+++++barrier+++++");
});
NSLog(@"紅成魔");
dispatch_async(queue, ^{
NSLog(@"%@ -- 3", [NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"%@ -- 4", [NSThread currentThread]);
});
NSLog(@"last");
}
打勇臀:
2021-04-02 14:47:27.971390+0800 343[9604:230587] start
2021-04-02 14:47:27.971691+0800 343[9604:230736] <NSThread: 0x600003fd63c0>{number = 5, name = (null)} -- 1
2021-04-02 14:47:27.971694+0800 343[9604:230741] <NSThread: 0x600003f95dc0>{number = 6, name = (null)} -- 2
2021-04-02 14:47:27.971879+0800 343[9604:230587] +++++barrier+++++
2021-04-02 14:47:27.972009+0800 343[9604:230587] 紅成魔
2021-04-02 14:47:27.972133+0800 343[9604:230587] last
2021-04-02 14:47:27.972187+0800 343[9604:230736] <NSThread: 0x600003fd63c0>{number = 5, name = (null)} -- 3
2021-04-02 14:47:27.972222+0800 343[9604:230741] <NSThread: 0x600003f95dc0>{number = 6, name = (null)} -- 4
再次打勇啪谩:
2021-04-02 14:48:53.684541+0800 343[9624:231947] start
2021-04-02 14:48:53.684813+0800 343[9624:232018] <NSThread: 0x60000076cd40>{number = 5, name = (null)} -- 2
2021-04-02 14:48:53.684818+0800 343[9624:232016] <NSThread: 0x60000076cd00>{number = 4, name = (null)} -- 1
2021-04-02 14:48:53.685010+0800 343[9624:231947] +++++barrier+++++
2021-04-02 14:48:53.685136+0800 343[9624:231947] 紅成魔
2021-04-02 14:48:53.685267+0800 343[9624:231947] last
2021-04-02 14:48:53.685370+0800 343[9624:232016] <NSThread: 0x60000076cd00>{number = 4, name = (null)} -- 4
2021-04-02 14:48:53.685371+0800 343[9624:232018] <NSThread: 0x60000076cd40>{number = 5, name = (null)} -- 3
2.換成dispatch_barrier_async
- (void)test {
//創(chuàng)建一個自定義并發(fā)隊列
NSLog(@"start");
dispatch_queue_t queue = dispatch_queue_create("CONCURRENT", DISPATCH_QUEUE_CONCURRENT);
//異步函數(shù) 無序執(zhí)行
dispatch_async(queue, ^{
NSLog(@"%@ -- 1", [NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"%@ -- 2", [NSThread currentThread]);
});
dispatch_barrier_async(queue, ^{
NSLog(@"+++++barrier+++++");
});
NSLog(@"紅成魔");
dispatch_async(queue, ^{
NSLog(@"%@ -- 3", [NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"%@ -- 4", [NSThread currentThread]);
});
NSLog(@"last");
}
執(zhí)行:
2021-04-02 14:50:46.552643+0800 343[9654:233393] start
2021-04-02 14:50:46.552857+0800 343[9654:233393] 紅成魔
2021-04-02 14:50:46.552908+0800 343[9654:233479] <NSThread: 0x600000912c00>{number = 3, name = (null)} -- 1
2021-04-02 14:50:46.553001+0800 343[9654:233393] last
2021-04-02 14:50:46.553004+0800 343[9654:233478] <NSThread: 0x600000911dc0>{number = 6, name = (null)} -- 2
2021-04-02 14:50:46.553180+0800 343[9654:233478] +++++barrier+++++
2021-04-02 14:50:46.553348+0800 343[9654:233478] <NSThread: 0x600000911dc0>{number = 6, name = (null)} -- 3
2021-04-02 14:50:46.553373+0800 343[9654:233479] <NSThread: 0x600000912c00>{number = 3, name = (null)} -- 4
再次執(zhí)行:
2021-04-02 14:51:46.928775+0800 343[9662:234265] start
2021-04-02 14:51:46.929065+0800 343[9662:234265] 紅成魔
2021-04-02 14:51:46.929210+0800 343[9662:234265] last
2021-04-02 14:51:46.929162+0800 343[9662:234331] <NSThread: 0x600001fd8bc0>{number = 7, name = (null)} -- 1
2021-04-02 14:51:46.929277+0800 343[9662:234337] <NSThread: 0x600001fd57c0>{number = 6, name = (null)} -- 2
2021-04-02 14:51:46.929812+0800 343[9662:234337] +++++barrier+++++
2021-04-02 14:51:46.930106+0800 343[9662:234337] <NSThread: 0x600001fd57c0>{number = 6, name = (null)} -- 3
2021-04-02 14:51:46.930148+0800 343[9662:234331] <NSThread: 0x600001fd8bc0>{number = 7, name = (null)} -- 4
9、線程同步
(http://www.reibang.com/p/4c4c5d3d4c10)
iOS線程同步方案性能從高到低排序爱榔,如下所示:
1被环、os_unfair_lock
os_unfair_lock用于取代不安全的OSSpinLock ,從iOS10開始才支持详幽,從底層調(diào)用看筛欢,等待os_unfair_lock鎖的線程會處于休眠狀態(tài),并非忙等狀態(tài)
2唇聘、OSSpinLock
OSSpinLock屬于”自旋鎖”版姑,等待鎖的線程會處于忙等(busy-wait)狀態(tài),一直占用著CPU資源迟郎,目前已經(jīng)不再安全剥险,可能會出現(xiàn)優(yōu)先級反轉(zhuǎn)問題:如果等待鎖的線程優(yōu)先級較高,它會一直占用著CPU資源谎亩,優(yōu)先級低的線程就無法釋放鎖
3炒嘲、dispatch_semaphore
semaphore叫做”信號量”
信號量的初始值,可以用來控制線程并發(fā)訪問的最大數(shù)量匈庭;
假設(shè)信號量的初始值為1夫凸,就代表同時只允許一條線程訪問資源
4、pthread_mutex
mutex屬于”互斥鎖”阱持,等待鎖的線程會處于休眠狀態(tài)
5夭拌、dispatch_queue(DISPATCH_QUEUE_SERIAL)
使用GCD的串行隊列,實現(xiàn)線程同步
6衷咽、NSLock
NSLock是對mutex普通鎖的封裝鸽扁,NSRecursiveLock也是對mutex遞歸鎖的封裝,API跟NSLock基本一致镶骗,NSCondition是對mutex和cond的封裝桶现,NSConditionLock是對NSCondition的進一步封裝,可以設(shè)置具體的條件值
7鼎姊、NSCondition
8骡和、pthread_mutex(recursive)
9相赁、NSRecursiveLock
10、NSConditionLock
11慰于、@synchronized
@synchronized是對mutex遞歸鎖的封裝钮科,源碼查看:objc4中的objc-sync.mm文件
@synchronized(obj)內(nèi)部會生成obj對應(yīng)的遞歸鎖,然后進行加鎖婆赠、解鎖操作
iOS中的讀寫安全方案(http://www.reibang.com/p/4c4c5d3d4c10)
1绵脯、pthread_rwlock:讀寫鎖
2、dispatch_barrier_async:異步柵欄調(diào)用
所謂線程同步就是為了防止多個線程搶奪同一個資源造成的數(shù)據(jù)安全問題休里,所采取的一種措施蛆挫。當(dāng)然也有很多實現(xiàn)方法,請往下看:
互斥鎖 :給需要同步的代碼塊加一個互斥鎖妙黍,就可以保證每次只有一個線程訪問此代碼塊璃吧。
OBJECTIVE-C
@synchronized(self) {
//需要執(zhí)行的代碼塊
}
SWIFT
objc_sync_enter(self)
//需要執(zhí)行的代碼塊
objc_sync_exit(self)
同步執(zhí)行 :我們可以使用多線程的知識,把多個線程都要執(zhí)行此段代碼添加到同一個串行隊列废境,這樣就實現(xiàn)了線程同步的概念。當(dāng)然這里可以使用 GCD 和 NSOperation 兩種方案筒繁,我都寫出來噩凹。
//GCD
//需要一個全局變量queue,要讓所有線程的這個操作都加到一個queue中
dispatch_sync(queue, ^{
NSInteger ticket = lastTicket;
[NSThread sleepForTimeInterval:0.1];
NSLog(@"%ld - %@",ticket, [NSThread currentThread]);
ticket -= 1;
lastTicket = ticket;
});
//NSOperation & NSOperationQueue
//重點:1. 全局的 NSOperationQueue, 所有的操作添加到同一個queue中
// 2. 設(shè)置 queue 的 maxConcurrentOperationCount 為 1
// 3. 如果后續(xù)操作需要Block中的結(jié)果毡咏,就需要調(diào)用每個操作的waitUntilFinished驮宴,阻塞當(dāng)前線程,一直等到當(dāng)前操作完成呕缭,才允許執(zhí)行后面的堵泽。waitUntilFinished 要在添加到隊列之后!
NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
NSInteger ticket = lastTicket;
[NSThread sleepForTimeInterval:1];
NSLog(@"%ld - %@",ticket, [NSThread currentThread]);
ticket -= 1;
lastTicket = ticket;
}];
[queue addOperation:operation];
[operation waitUntilFinished];
//后續(xù)要做的事
延遲執(zhí)行
所謂延遲執(zhí)行就是延時一段時間再執(zhí)行某段代碼恢总。下面說一些常用方法迎罗。
OBJECTIVE-C
// 3秒后自動調(diào)用self的run:方法,并且傳遞參數(shù):@"abc"
[self performSelector:@selector(run:) withObject:@"abc" afterDelay:3];
SWIFT
之前就已經(jīng)說過片仿,Swift 里去掉了這個方法纹安。
GCD
可以使用 GCD 中的 dispatch_after 方法,OC 和 Swift 都可以使用砂豌,這里只寫 OC 的厢岂,Swift 的是一樣的。
// 創(chuàng)建隊列
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
// 設(shè)置延時阳距,單位秒
double delay = 3;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)), queue, ^{
// 3秒后需要執(zhí)行的任務(wù)
});
NSTimer
NSTimer 是iOS中的一個計時器類塔粒,除了延遲執(zhí)行還有很多用法,不過這里直說延遲執(zhí)行的用法筐摘。同樣只寫 OC 版的卒茬,Swift 也是相同的船老。
[NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(run:) userInfo:@"abc" repeats:NO];