iOS 的多執行緒方案大致有四種:pthread、NSThread、GCD、NSOperation。本文先把前三種的基礎用法與 GCD 的各種組合講透,NSOperation 留待下一篇。
跨平台、可攜性佳,本質是 C 語言 API,執行緒生命週期完全由開發者管理。
// 子執行緒要執行的函式
void *run(void *pramga) {
NSLog(@"-------");
return NULL;
}
- (IBAction)btnClick:(id)sender {
pthread_t pthread;
pthread_create(&pthread, NULL, run, NULL);
}
物件導向、簡單實用。有三種建立方式:
// 1. 隱式建立並立即啟動
[NSThread detachNewThreadSelector:@selector(threadRun:)
toTarget:self
withObject:@"etund"];
// 2. 在背景執行
[self performSelectorInBackground:@selector(threadRun:) withObject:@"etund"];
// 3. 先建立再啟動(可設定 stackSize、name 等屬性)
NSThread *thread = [[NSThread alloc] initWithTarget:self
selector:@selector(threadRun:)
object:@"etund"];
[thread start];
前兩種方便快捷,但無法在啟動前設定額外屬性;第三種可以,代價是要自己呼叫 start。
GCD 是 Apple 為多核平行運算提出的方案,優勢很明確:
理解 GCD 的關鍵是兩件事:任務與佇列。另外要記住一個容易搞錯的觀念——序列/並行決定的是「能不能開新執行緒」,同步/非同步決定的是「要不要開新執行緒」。並行代表具備開新執行緒的能力,但不一定真的開。
這三種都不會開子執行緒,任務在主執行緒上按順序執行。
// 序列佇列
dispatch_queue_t queue = dispatch_queue_create("etund", DISPATCH_QUEUE_SERIAL);
// 並行佇列
// dispatch_queue_t queue = dispatch_queue_create("etund", DISPATCH_QUEUE_CONCURRENT);
dispatch_sync(queue, ^{ NSLog(@"%@---1", [NSThread currentThread]); });
dispatch_sync(queue, ^{ NSLog(@"%@----2", [NSThread currentThread]); });
dispatch_sync(queue, ^{ NSLog(@"%@----3", [NSThread currentThread]); });
輸出:
<NSThread: {...} {number = 1, name = main}---1
<NSThread: {...} {number = 1, name = main}----2
<NSThread: {...} {number = 1, name = main}----3
三個任務都在 main 執行緒上,順序執行。
開啟一條子執行緒,任務在其上按順序執行。
dispatch_queue_t queue = dispatch_queue_create("etund", DISPATCH_QUEUE_SERIAL);
dispatch_async(queue, ^{ NSLog(@"%@---1", [NSThread currentThread]); });
dispatch_async(queue, ^{ NSLog(@"%@---2", [NSThread currentThread]); });
dispatch_async(queue, ^{ NSLog(@"%@---3", [NSThread currentThread]); });
輸出:
<NSThread: {...} {number = 3, name = (null)}---1
<NSThread: {...} {number = 3, name = (null)}---2
<NSThread: {...} {number = 3, name = (null)}---3
三個任務都在同一條子執行緒(number = 3)上,順序不亂。
具備開多條子執行緒的能力,實際會開幾條由系統決定。任務從佇列取出放入執行緒的順序仍是先進先出,但完成順序不定。
dispatch_queue_t queue = dispatch_queue_create("etund", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue, ^{ NSLog(@"%@---1", [NSThread currentThread]); });
dispatch_async(queue, ^{ NSLog(@"%@---2", [NSThread currentThread]); });
dispatch_async(queue, ^{ NSLog(@"%@---3", [NSThread currentThread]); });
輸出(順序可能不同):
<NSThread: {...} {number = 4, name = (null)}---2
<NSThread: {...} {number = 5, name = (null)}---3
<NSThread: {...} {number = 3, name = (null)}---1
不開任何子執行緒,任務排進主佇列依次執行。這正好印證了那句話:非同步佇列只是「具備」開子執行緒的能力,並不代表一定會開。
dispatch_async(dispatch_get_main_queue(), ^{ NSLog(@"%@---1", [NSThread currentThread]); });
dispatch_async(dispatch_get_main_queue(), ^{ NSLog(@"%@---2", [NSThread currentThread]); });
dispatch_async(dispatch_get_main_queue(), ^{ NSLog(@"%@---3", [NSThread currentThread]); });
- (void)gcdTest_2_4 {
NSLog(@"=-=-=-");
dispatch_sync(dispatch_get_main_queue(), ^{ NSLog(@"%@---1", [NSThread currentThread]); });
NSLog(@"=-=-=-");
}
在主執行緒上对主佇列做 dispatch_sync 會造成死鎖——後面的程式永遠不會執行。這是需要絕對避開的寫法。
當後續步驟必須等前面幾個步驟都完成時,用 dispatch_group 或 barrier 都能解決。
dispatch_queue_t queue =
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_t group = dispatch_group_create();
// 下載圖片 1
dispatch_group_async(group, queue, ^{
NSURL *url = [NSURL URLWithString:@"https://f.hiphotos.baidu.com/image/pic/item/d788d43f8794a4c2e882eb8b0df41bd5ac6e39e8.jpg"];
NSData *data = [NSData dataWithContentsOfURL:url];
self.image1 = [UIImage imageWithData:data];
});
// 下載圖片 2
dispatch_group_async(group, queue, ^{
NSURL *url = [NSURL URLWithString:@"https://h.hiphotos.baidu.com/image/pic/item/ac6eddc451da81cbd668501c5666d01608243151.jpg"];
NSData *data = [NSData dataWithContentsOfURL:url];
self.image2 = [UIImage imageWithData:data];
});
// 兩張都下載完才合併
dispatch_group_notify(group, queue, ^{
UIGraphicsBeginImageContextWithOptions(CGSizeMake(100, 100), NO, 0);
[self.image1 drawAsPatternInRect:CGRectMake(0, 0, 50, 100)];
[self.image2 drawAsPatternInRect:CGRectMake(50, 0, 50, 100)];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// 回到主執行緒更新 UI
dispatch_async(dispatch_get_main_queue(), ^{
self.myView.image = image;
});
});
dispatch_queue_t queue =
dispatch_queue_create("etund", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue, ^{ /* 下載圖片 1 */ });
dispatch_async(queue, ^{ /* 下載圖片 2 */ });
// 柵欄:等前面全部完成,且後續任務要等它完成
dispatch_barrier_async(queue, ^{});
dispatch_async(queue, ^{
// 合併圖片並回主執行緒更新
});
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)),
dispatch_get_main_queue(), ^{
// 2 秒後執行
});
不在意順序、只想盡快處理完所有子元素時使用。
dispatch_queue_t queue =
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_apply(self.view.subviews.count, queue, ^(size_t index) {
id obj = self.view.subviews[index];
NSLog(@"---%zu---%@", index, obj);
});
單例設計最關鍵的一點是執行緒安全,GCD 提供了現成的解法。
// ETPerson.m
@implementation ETPerson
static ETPerson *_person;
+ (instancetype)sharePerson {
static dispatch_once_t onceDispatch;
dispatch_once(&onceDispatch, ^{
_person = [[ETPerson alloc] init];
});
return _person;
}
// 防止外部用 alloc/copy 另建實例
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
static dispatch_once_t onceDispatch;
dispatch_once(&onceDispatch, ^{
_person = [super allocWithZone:zone];
});
return _person;
}
- (id)copyWithZone:(NSZone *)zone {
return _person;
}
@end
同一個行程內常有多條執行緒,它們之間需要交換資料或接力完成任務。
NSThread 的做法:
// 在當前執行緒任務結束後,切回主執行緒執行
- (void)performSelectorOnMainThread:(SEL)aSelector
withObject:(id)arg
waitUntilDone:(BOOL)wait;
// 切到指定執行緒執行
- (void)performSelector:(SEL)aSelector
onThread:(NSThread *)thr
withObject:(id)arg
waitUntilDone:(BOOL)wait;
GCD 的做法更直觀——把更新 UI 的程式碼包進主佇列的 dispatch_async 即可:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// 耗時的非同步操作
dispatch_async(dispatch_get_main_queue(), ^{
// 回到主執行緒更新 UI
});
});
至此,iOS 中 pthread、NSThread 與 GCD 的核心部分就整理完了,下一篇再談 NSOperation。