
本文是投稿文章,作者:小笨狼。
多線程是開發中基礎但容易出錯的主題。iOS 常見方案有 NSThread、GCD、NSOperation。本文聚焦 NSThread,因為它最直接對應 thread 概念。
thread 是程式碼獨立執行的路徑;process 是可執行中的實例,可包含多個 thread。當一個程式有多條執行路徑同時運行,就是多線程。
NSThread 可用 detachNewThreadSelector 直接建立並啟動,也可用 initWithTarget 建立後手動 start。
self.thread = [[NSThread alloc] initWithTarget:self selector:@selector(threadMain) object:nil]; self.thread.qualityOfService = NSQualityOfServiceDefault; [self.thread start];
qualityOfService 這類屬性要在啟動前設定,啟動後再改可能無效。
sleepUntilDate 與 sleepForTimeInterval 可讓執行緒暫停。取消方面,-cancel 不會真的終止執行緒,只是把 cancelled 設為 YES;程式必須在 main 函數中自行檢查並退出。
-exit 會立即終止執行緒,但可能導致資源未釋放,因此不建議任意使用。
常見做法是透過 performSelector 系列方法,把任務丟到指定執行緒,完成後再回到主執行緒更新 UI。
[self performSelector:@selector(threadTask) onThread:self.thread withObject:nil waitUntilDone:NO]
注意:perform 方法依賴 runloop。如果自訂執行緒沒有 runloop,相關 selector 可能不會執行。
NSThread 提供 threadPriority 與 qualityOfService。iOS 8 之後更推薦使用 NSQualityOfService,例如 UserInteractive、UserInitiated、Default、Utility、Background。
可用 isMainThread 判斷是否為主執行緒,也可用 mainThread 取得主執行緒。NSThreadWillExitNotification 會在執行緒退出前送出。
若希望執行緒不要執行完就退出,可以在 threadMain 中加入 runloop:
- (void)threadMain {
[[NSThread currentThread] setName:@"myThread"];
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
[runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];
while (![[NSThread currentThread] isCancelled]) {
[runLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:10]];
}
}
結束執行緒時,可搭配 -cancel 與 CFRunLoopStop。但要注意,只有 runMode:beforeDate: 啟動的 runloop 才能可靠回應 CFRunLoopStop。
延伸閱讀可參考 ibireme 的 RunLoop 文章,以及 AFNetworking 2 的源碼。