在這篇文章中,我將為你系統梳理 iOS 開發中的幾套多線程方案及其使用方法與注意事項,並輔以實際案例,幫助你在實踐中體會它們的區別。需要說明的是,本文同時採用 Swift 與 Objective-C 兩種語言講解。OK,let's begin!
概述
本文不會糾結「多線程是什麼」「線程與進程的區別」「串行與並行」這些基礎概念,這些我們理應已經掌握。
在 iOS 中,目前主要有 4 套多線程方案:
接下來我會逐一講解它們的用法與案例,並順帶談及線程同步、延時執行、單例模式等多線程周邊知識。
Pthreads
這套方案只是拿來充數,讓大家了解一下即可。百度百科是這樣描述的:POSIX 線程(POSIX threads),簡稱 Pthreads,是線程的 POSIX 標準,定義了創建和操縱線程的一整套 API。在類 Unix 操作系統(Unix、Linux、Mac OS X 等)中,都以 Pthreads 作為操作系統的線程。
簡單說,這是一套在眾多操作系統上通用的多線程 API,移植性很強,在 iOS 中當然也能用。但由於它是基於 C 語言的框架,使用起來頗為繁瑣——它需要 C 語言函數,且要手動管理線程各狀態的轉換(即生命周期)。例如它創建了一個線程,卻不會自動銷毀。遺憾的是,在早期 Swift 中還無法直接使用它,因為該函數需要傳入 C 函數指針(CFunctionPointer),而 Swift 當時無法將方法轉為此類型(後續 Swift 2.0 引入的 @convention(c) 特性可解決此問題)。總之,做 iOS 開發幾乎不會用到 Pthreads,除非你想從底層定製一套多線程方案。
NSThread
這套方案經過蘋果封裝,完全面向對象,可以直接操控線程對象,直觀方便。但它的生命周期仍需手動管理,所以偶爾用用即可。比如 [NSThread currentThread] 可獲取當前線程,便於調試。下面看看常見用法。
創建並啟動
先創建線程類,再啟動:
//Objective-C NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run:) object:nil]; [thread start]; //Swift let thread = NSThread(target: self, selector: "run:", object: nil) thread.start()
創建並自動啟動:
//Objective-C [NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:nil]; //Swift NSThread.detachNewThreadSelector("run:", toTarget: self, withObject: nil)
使用 NSObject 的方法創建並自動啟動:
//Objective-C [self performSelectorInBackground:@selector(run:) withObject:nil]; //Swift 遺憾的是,蘋果認為 performSelector: 不安全,在 Swift 中去掉了這個方法。
其他常用方法
除創建與啟動外,NSThread 還有不少方法,列舉一些常見的:
-(void)cancel; //取消線程 -(void)start; //啟動線程 @property(readonly, getter=isExecuting) BOOL executing; @property(readonly, getter=isFinished) BOOL finished; @property(readonly, getter=isCancelled) BOOL cancelled; -(void)setName:(NSString *)n; -(NSString *)name; +(NSThread *)currentThread; //獲取當前線程 +(NSThread *)mainThread; //獲取主線程 +(void)sleepForTimeInterval:(NSTimeInterval)time; //暫停一段時間 +(void)sleepUntilDate:(NSDate *)date; //暫停到某個時刻
Swift 的方法名與 OC 基本一致,這裡不再贅述。NSThread 只在一些非常簡單的場景才會用到,畢竟它還不夠智能,無法優雅地處理多線程中的高級概念。接下來的內容才是重點。
GCD
Grand Central Dispatch,聽名字就霸氣。它是蘋果為多核並行運算提出的解決方案,會自動合理地利用更多 CPU 內核,最重要的是它會自動管理線程的生命周期(創建、調度、銷毀),我們只需告訴它「做什麼」即可。它同樣基於 C 語言,但借助 Block(Swift 中稱閉包),使用起來更加方便靈活,因此成為大家的首選。
任務與隊列
GCD 引入了兩個核心概念:任務與隊列。
任務:即操作,也就是一段代碼(在 GCD 中就是一個 Block)。任務有兩種執行方式——同步執行與異步執行,二者的關鍵區別在於是否阻塞當前線程:
同步(sync):會阻塞當前線程,直到 Block 中的任務執行完畢,當前線程才會繼續往下執行。
異步(async):當前線程會直接往下執行,不會阻塞。
隊列:用於存放任務,分為串行隊列與並行隊列。
串行隊列中的任務按 FIFO(先進先出)一個接一個執行。
並行隊列中的任務,GCD 也會 FIFO 地取出,但每取出一個就放到另一條線程執行,由於取動作極快、可忽略,看起來就像所有任務同時執行。不過 GCD 會根據系統資源控制並行數量,任務很多時不會讓它們全部同時執行。

創建隊列
主隊列:一個特殊的串行隊列,用於刷新 UI,任何需要更新 UI 的工作都必須在主隊列執行,因此耗時任務要放到別的線程。
//Objective-C dispatch_queue_t queue = dispatch_get_main_queue(); //Swift let queue = dispatch_get_main_queue()
自己創建的隊列:可以創建串行隊列,也可以創建並行隊列。第二個參數最為關鍵——傳入 DISPATCH_QUEUE_SERIAL 或 NULL 表示串行隊列,傳入 DISPATCH_QUEUE_CONCURRENT 表示並行隊列。
//Objective-C dispatch_queue_t queue = dispatch_queue_create("tk.bourne.testQueue", NULL); //Swift let queue = dispatch_queue_create("tk.bourne.testQueue", nil)
全局並行隊列:這是唯一內建的並行隊列,並行任務一般都加入這裡。
//Objective-C dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); //Swift let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
創建任務
同步任務(不會另開線程):
dispatch_sync(queue, ^{ NSLog(@"%@", [NSThread currentThread]); });
異步任務(會另開線程):
dispatch_async(queue, ^{ NSLog(@"%@", [NSThread currentThread]); });
兩個經典示例
示例一:以下代碼在主線程調用,結果如何?
NSLog(@"之前-%@", NSThread.currentThread()) dispatch_sync(dispatch_get_main_queue(), ^{ NSLog(@"sync-%@", NSThread.currentThread()); }); NSLog(@"之後-%@", NSThread.currentThread());
答案:只會打印第一句「之前」,然後主線程卡死。這是因為 dispatch_sync 立即阻塞主線程,又把 Block 任務放進 main_queue,而 main_queue 的任務需要在主線程執行——但主線程已被阻塞,於是 Block 永遠無法完成,dispatch_sync 便一直阻塞主線程,形成死鎖。
示例二:以下代碼會產生什麼結果?
let queue = dispatch_queue_create("myQueue", DISPATCH_QUEUE_SERIAL) NSLog(@"之前-%@", NSThread.currentThread()) dispatch_async(queue, ^{ NSLog(@"sync之前-%@", NSThread.currentThread()); dispatch_sync(queue, ^{ NSLog(@"sync-%@", NSThread.currentThread()); }); NSLog(@"sync之後-%@", NSThread.currentThread()); }); NSLog(@"之後-%@", NSThread.currentThread());
答案:「sync」和「sync之後」都不會被打印。分析:異步任務在另一條線程執行,打印「sync之前」後遇到 dispatch_sync,於是阻塞當前線程等待 Block 完成;可 Block 被放進同一個串行隊列,必須等前一個任務(正是被阻塞的那個)執行完才能輪到它,於是再次死鎖,該線程被卡死,後續兩句自然不會打印。
隊列組
隊列組可以把多個隊列加入同一組,當組內所有任務都執行完,會通過一個方法通知我們,非常實用。
//1.創建隊列組 dispatch_group_t group = dispatch_group_create(); //2.創建隊列 dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); //3.多次使用隊列組的異步方法執行任務 dispatch_group_async(group, queue, ^{ /* 任務 */ }); //4.都完成後自動通知 dispatch_group_notify(group, dispatch_get_main_queue(), ^{ NSLog(@"完成-%@", [NSThread currentThread]); });
關於 GCD,還有兩個屏障方法值得了解:
dispatch_barrier_async:當傳入的是通過 DISPATCH_QUEUE_CONCURRENT 自定義的並發隊列時,它會阻塞這個 queue(注意是阻塞 queue 而非線程),等到排在其前面的任務都完成後才執行自己,執行完再解除阻塞,讓後續任務繼續。若傳入其他 queue,則等同 dispatch_async。
dispatch_barrier_sync:用法與上者相同,傳入自定義並發隊列時同樣阻塞 queue,不同的是它還會阻塞當前線程。若傳入其他 queue,則等同 dispatch_sync。
NSOperation 和 NSOperationQueue
NSOperation 是蘋果對 GCD 的封裝,完全面向對象,更好理解。可以看到 NSOperation 與 NSOperationQueue 分別對應 GCD 的任務與隊列。使用步驟很清晰:先把任務封裝進 NSOperation 對象,再把它添加到 NSOperationQueue 中,系統便會自動執行。
添加任務
NSOperation 是抽象類,不能直接封裝任務,但它有兩個子類:NSInvocationOperation 與 NSBlockOperation。創建 Operation 後調用 start 方法啟動,默認在當前線程同步執行,也可隨時調用 cancel 取消。
NSInvocationOperation:需傳入一個方法名。
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(run) object:nil]; [operation start];
NSBlockOperation:
NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{ NSLog(@"%@", [NSThread currentThread]); }]; [operation start];
NSBlockOperation 還有一個 addExecutionBlock: 方法,可為同一 Operation 添加多個執行 Block,此時任務會並發執行,在主線程與多個線程中同時跑(注意 addExecutionBlock 必須在 start 之前調用,否則報錯):
NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{ NSLog(@"%@", [NSThread currentThread]); }]; for (NSInteger i = 0; i < 5; i++) { [operation addExecutionBlock:^{ NSLog(@"第%ld次:%@", i, [NSThread currentThread]); }]; } [operation start];
小提示:Swift 中用 print()/println() 輸出時,由於其基於「流」逐字符輸出,多線程同步打印時容易導致控制台字符錯亂堆疊;而 NSLog() 沒有這個問題。
創建隊列
直接調用某個 NSOperation 的 start() 啟動任務,默認是同步執行的(即便用了 addExecutionBlock,也會佔用當前線程)。這時就需要 NSOperationQueue 了。隊列分兩類:主隊列與其他隊列,任務一旦加入隊列,會自動調用其 start() 方法。
主隊列:特殊的串行隊列,任務一個接一個在主線程處理。
//Objective-C NSOperationQueue *queue = [NSOperationQueue mainQueue]; //Swift let queue = NSOperationQueue.mainQueue()
其他隊列:通過初始化產生,其任務會在其他線程並行執行。
NSOperationQueue *queue = [[NSOperationQueue alloc] init]; NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{ NSLog(@"%@", [NSThread currentThread]); }]; for (NSInteger i = 0; i < 5; i++) { [operation addExecutionBlock:^{ NSLog(@"第%ld次:%@", i, [NSThread currentThread]); }]; } [queue addOperation:operation];
細心的讀者會發現,NSOperationQueue 沒有並行隊列的概念。那如果想讓 10 個任務在其他線程串行執行怎麼辦?這正是蘋果封裝的巧妙之處——你無需糾結串行、並行、同步、異步這些名詞,只需設置 maxConcurrentOperationCount(最大並發數)。把它設為 1,任務自然就串行了。此外,- (void)addOperationWithBlock:(void (^)(void))block; 讓你能便捷地向隊列添加任務。
NSOperation 還有一個非常實用的功能——添加依賴。例如三個任務:A 下載圖片、B 給圖片加水印、C 上傳圖片,便可通過依賴串聯:
NSBlockOperation *operation1 = [NSBlockOperation blockOperationWithBlock:^{ NSLog(@"下載圖片-%@", [NSThread currentThread]); [NSThread sleepForTimeInterval:1.0]; }]; NSBlockOperation *operation2 = [NSBlockOperation blockOperationWithBlock:^{ NSLog(@"打水印-%@", [NSThread currentThread]); [NSThread sleepForTimeInterval:1.0]; }]; NSBlockOperation *operation3 = [NSBlockOperation blockOperationWithBlock:^{ NSLog(@"上傳圖片-%@", [NSThread currentThread]); [NSThread sleepForTimeInterval:1.0]; }]; [operation2 addDependency:operation1]; //任務二依賴任務一 [operation3 addDependency:operation2]; //任務三依賴任務二 NSOperationQueue *queue = [[NSOperationQueue alloc] init]; [queue addOperations:@[operation3, operation2, operation1] waitUntilFinished:NO];
注意:不能添加相互依賴(如 A 依賴 B、B 又依賴 A),否則會死鎖;可用 removeDependency 解除依賴;依賴可跨隊列添加,因為它添加到任務本身而非隊列。
其他常用方法
NSOperation:executing(是否正在執行)、finished(是否完成)、completionBlock(完成後的操作)、cancel(取消任務)、waitUntilFinished(阻塞當前線程直到任務完成)。
NSOperationQueue:operationCount(任務數)、cancelAllOperations(取消所有任務)、waitUntilAllOperationsAreFinished(阻塞直到所有任務完成)、setSuspended:(暫停/恢復 queue)。
其他用法
下面介紹一些與多線程相關的實用案例。
線程同步
線程同步是為了防止多個線程爭搶同一資源造成數據安全問題而採取的措施,常見實現如下:
互斥鎖:給需要同步的代碼塊加鎖,保證每次只有一個線程訪問。
//Objective-C @synchronized(self) { //需要同步的代碼塊 } //Swift objc_sync_enter(self) //需要同步的代碼塊 objc_sync_exit(self)
同步執行:把多個線程都要執行的同一段代碼添加到同一個串行隊列,即可實現線程同步(GCD 與 NSOperation 均可)。
//GCD dispatch_sync(queue, ^{ NSInteger ticket = lastTicket; [NSThread sleepForTimeInterval:0.1]; NSLog(@"%ld-%@", ticket, [NSThread currentThread]); ticket -= 1; lastTicket = ticket; }); //NSOperation & NSOperationQueue: 全局 NSOperationQueue + maxConcurrentOperationCount 設為 1 + 需要時調用 waitUntilFinished(添加到隊列之後)
延遲執行
延遲執行即延時一段時間後再執行某段代碼,常用方式如下。
perform:
//3秒後自動調用 self 的 run: 方法並傳參 @"abc" [self performSelector:@selector(run:) withObject:@"abc" afterDelay:3]; //Swift 中已移除該方法
GCD 的 dispatch_after(OC 與 Swift 通用):
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); double delay = 3; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)), queue, ^{ //3秒後需要執行的任務 });
NSTimer:
[NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(run:) userInfo:@"abc" repeats:NO];
單例模式
Objective-C 中實現單例的標準寫法如下(用到了 GCD 的 dispatch_once):
@interface Tool : NSObject + (instancetype)sharedTool; @end @implementation Tool static id _instance; + (instancetype)sharedTool { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _instance = [[Tool alloc] init]; }); return _instance; } @end
而在 Swift 中,單例模式變得非常簡單:
class Tool: NSObject { static let sharedTool = Tool() //私有化構造方法,阻止外部使用默認的 () 構造 private override init(){} }
從其他線程回到主線程
我們都知道,在其他線程完成操作後必須回到主線程更新 UI,常見方式如下。
NSThread:
[self performSelectorOnMainThread:@selector(run) withObject:nil waitUntilDone:NO]; //Swift 取消了 performSelector 方法
GCD:
dispatch_async(dispatch_get_main_queue(), ^{ }); //Swift: dispatch_async(dispatch_get_main_queue(), { () -> Void in })
NSOperationQueue:
[[NSOperationQueue mainQueue] addOperationWithBlock:^{ }]; //Swift: NSOperationQueue.mainQueue().addOperationWithBlock { () -> Void in }