寫 iOS 時有一條鐵則:所有跟 UI 相關的更新與操作,都必須在主執行緒(main thread)進行。一旦網路請求、檔案讀寫、大量運算這類耗時任務也塞在主執行緒,畫面就會卡住。這正是子執行緒存在的意義。
當 App 剛啟動時,系統會自動配置一條執行緒,即主執行緒;其餘則需由開發者自行建立。
C 語言層級的 POSIX 執行緒,是最底層的做法:
pthread_t pthread; // 參數一:執行緒指標 // 參數二:執行緒屬性 // 參數三:函式指標,即執行緒的進入點 // 參數四:傳入參數 pthread_create(&pthread, NULL, run, NULL);
Objective-C 的封裝,有兩種建立方式。
方式一,先建立物件再啟動:
NSThread *thread = [[NSThread alloc] initWithTarget:self
selector:@selector(doWork)
object:@"123"];
thread.name = @"worker"; // 命名有助於除錯
[thread start];方式二,一句話建立並立即執行:
[NSThread detachNewThreadSelector:@selector(doWork)
toTarget:self
withObject:@"456"];
[self performSelectorInBackground:@selector(doWork)
withObject:@"123"];若需要讓當前執行緒暫停,可用:
[NSThread sleepForTimeInterval:0.5];
NSOperation 是抽象類別,實務上不會直接用它,而是使用兩個子類別:NSInvocationOperation 與 NSBlockOperation。關鍵觀念是:單獨執行時它們跑在主執行緒,只有放進佇列才會在子執行緒執行。
NSInvocationOperation *op1 = [[NSInvocationOperation alloc]
initWithTarget:self selector:@selector(action1) object:nil];
NSInvocationOperation *op2 = [[NSInvocationOperation alloc]
initWithTarget:self selector:@selector(action2) object:nil];
NSBlockOperation *op3 = [NSBlockOperation blockOperationWithBlock:^{
for (int i = 20; i < 30; i++) {
NSLog(@"%d", i);
}
}];
// [NSOperationQueue mainQueue] 代表主佇列;
// 若用 alloc/init,則是背景佇列
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[queue addOperation:op1];
[queue addOperation:op2];
[queue addOperation:op3];加入佇列的順序決定「開始排隊」的先後,但完成順序不保證——後加入的有可能先跑完。若需要控制先後,得靠 addDependency: 或 NSOperationQueue 的 maxConcurrentOperationCount。
GCD 是 Grand Central Dispatch,四個基本概念:
把這四者交叉組合,行為各不相同:
同步 + 主佇列 :所有提交到主佇列的任務必須是異步的, 否則會造成死鎖 異步 + 主佇列 :不開新執行緒,就在主執行緒執行(主佇列是序列的) 同步 + 序列佇列 :不具備開啟執行緒的能力,在目前執行緒完成任務 異步 + 序列佇列 :能開啟執行緒,但任務序列執行,一個接一個 同步 + 並行佇列 :不具備開啟執行緒的能力,並發效果形同虛設
並行佇列的兩種建立方式:
dispatch_queue_t q1 = dispatch_queue_create("com.demo.worker", DISPATCH_QUEUE_CONCURRENT);
dispatch_queue_t q2 = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);典型寫法是「背景佇列抓資料,主佇列更新 UI」:
- (void)viewDidLoad {
[super viewDidLoad];
dispatch_queue_t queue = dispatch_queue_create("com.demo.download", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue, ^{
NSURL *url = [NSURL URLWithString:@"https://example.com/image.jpg"];
NSData *data = [NSData dataWithContentsOfURL:url];
dispatch_sync(dispatch_get_main_queue(), ^{
self.imageView.image = [UIImage imageWithData:data];
});
});
}延遲執行:
void dispatch_after(dispatch_time_t when,
dispatch_queue_t queue,
dispatch_block_t block);重複執行:以下方法為同步返回,也就是所有 block 都跑完才會回傳;若要異步,需包在 dispatch_async 裡使用。至於這些 block 是並發還是序列,取決於傳入的 queue 屬性。
void dispatch_apply(size_t iterations,
dispatch_queue_t queue,
void (^block)(size_t));