iOS 提供了三套多執行緒工具,年代一層比一層新,抽象層一層比一層高。用同一個「多執行緒賣票」的問題把它們跑一遍,差異會非常清楚。
建立並啟動一條執行緒:
// 三個參數:目標類、目標方法、傳給該方法的參數
NSThread *thread = [[NSThread alloc] initWithTarget:self
selector:@selector(saleTicketMethod:)
object:@"線程--1"];
[thread start];
iOS 和 Android 一樣是執行緒不安全平台,所有 UI 更新都必須在主執行緒完成。要從背景執行緒改畫面:
// 參數一:目標方法;參數二:傳遞的物件(只能一個);參數三:是否同步等待
[self performSelectorOnMainThread:@selector(updateView:)
withObject:str
waitUntilDone:YES];
不同執行緒搶同一份資源時必須自己加鎖:
@interface CSZViewController ()
{
int _ticketNum;
NSLock *_lock;
}
@end
@implementation CSZViewController
- (void)updateView:(NSString *)text {
NSString *str = [NSString stringWithFormat:@"%@ \n%@", self.textView.text, text];
self.textView.text = str;
}
- (void)saleTicketMethod:(NSString *)threadName {
while (true) {
if (_ticketNum > 0) {
[_lock lock];
NSString *str = [NSString stringWithFormat:@"%@線程的票數為:%d", threadName, _ticketNum];
[self performSelectorOnMainThread:@selector(updateView:) withObject:str waitUntilDone:YES];
_ticketNum--;
[_lock unlock];
if ([threadName isEqualToString:@"線程--1"]) {
[NSThread sleepForTimeInterval:1.0];
} else {
[NSThread sleepForTimeInterval:2.0];
}
} else {
NSString *str = [NSString stringWithFormat:@"售票結束!%@", threadName];
[self performSelectorOnMainThread:@selector(updateView:) withObject:str waitUntilDone:YES];
break;
}
}
}
- (IBAction)threadClick:(id)sender {
_ticketNum = 20;
_lock = [[NSLock alloc] init];
NSThread *thread = [[NSThread alloc] initWithTarget:self
selector:@selector(saleTicketMethod:)
object:@"線程--1"];
NSThread *thread1 = [[NSThread alloc] initWithTarget:self
selector:@selector(saleTicketMethod:)
object:@"線程--2"];
[thread start];
[thread1 start];
}
@end
這段程式碼有個值得注意的細節:加鎖的範圍包含了 performSelectorOnMainThread:...waitUntilDone:YES。如果主執行緒此刻正好也在等這把鎖,就會形成死鎖。實務上應該只把「讀取與遞減」這幾行包進鎖裡,UI 更新移到鎖外。
NSOperation 把執行緒的生命週期、資源競爭與排隊都封裝起來,你只要描述「要做什麼」。
1. 建立佇列並限制併發數
NSOperationQueue *queue = [[NSOperationQueue alloc] init]; // 同時最多跑 5 條,就像 Java 的線程池 [queue setMaxConcurrentOperationCount:5];
2. 定義非同步任務
NSInvocationOperation *opera = [[NSInvocationOperation alloc]
initWithTarget:self selector:@selector(operaSaleMethod:) object:@"線程操作1"];
NSInvocationOperation *opera2 = [[NSInvocationOperation alloc]
initWithTarget:self selector:@selector(operaSaleMethod:) object:@"線程操作2"];
3. 放進佇列,由佇列自動配置
[queue addOperation:opera]; [queue addOperation:opera2];
4. 操作內部不需要自己加鎖
- (void)operaSaleMethod:(NSString *)threadName {
while (true) {
if (_ticketNum > 0) {
if ([threadName isEqualToString:@"線程操作1"]) {
[NSThread sleepForTimeInterval:2.0];
} else {
[NSThread sleepForTimeInterval:1.2];
}
NSString *str = [NSString stringWithFormat:@"%@線程的票數為:%d", threadName, _ticketNum];
[self performSelectorOnMainThread:@selector(updateView:) withObject:str waitUntilDone:YES];
_ticketNum--;
} else {
NSString *str = [NSString stringWithFormat:@"%@售票結束!", threadName];
[self performSelectorOnMainThread:@selector(updateView:) withObject:str waitUntilDone:YES];
break;
}
}
}
這裡要修正一個常見誤解:NSOperation 並沒有幫你做「同一份資料的互斥」。它省掉的是執行緒的建立與回收,不是資料競爭。上面的寫法之所以沒問題,是因為兩段 sleep 長度不同、加上操作順序恰好錯開,屬於僥倖;正確做法仍然是在遞減前加鎖,或使用 NSLock/@synchronized。NSOperation 真正提供的好東西是相依性(addDependency:)、取消(cancel)與完成通知(completionBlock)。
1. 取得佇列
// DISPATCH_QUEUE_PRIORITY_HIGH = 2 // DISPATCH_QUEUE_PRIORITY_DEFAULT = 0 // DISPATCH_QUEUE_PRIORITY_LOW = -2 // DISPATCH_QUEUE_PRIORITY_BACKGROUND = INT16_MIN dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
2. 建立群組
dispatch_group_t group = dispatch_group_create();
3. 加入非同步任務
dispatch_group_async(group, queue, ^{
[self gcdSaleMethod:@"線程操作1"];
});
dispatch_group_async(group, queue, ^{
[self gcdSaleMethod:@"線程操作2"];
});
4. 等全部完成後收到通知
dispatch_group_notify(group, queue, ^{
NSLog(@"線程操作完成");
});
實際執行的紀錄看起來像這樣,notify 的 block 一定是最後才跑:
2014-08-11 15:08:38.982 ThreadSample01[5256:4007] 線程操作2售票結束! 2014-08-11 15:08:39.037 ThreadSample01[5256:1903] 線程操作1售票結束! 2014-08-11 15:08:39.042 ThreadSample01[5256:4007] 線程操作完成
GCD 相比 NSOperation 多了「群組」的概念,程式碼也更精簡;代價是取消與相依性得自己用旗標實作。另外 block 內對 self 的強參考要留意,若佇列又持有這個 block,容易形成循環參考。
今天幾乎沒有理由再用 NSThread 直接開執行緒,它唯一的價值是用來理解「一條執行緒到底是什麼」。GCD 適合「做完就好」的一次性任務,程式碼短、效能好;NSOperation 適合需要取消、需要排定先後順序、或需要觀察單一任務狀態的情境,例如序列化的網路請求佇列。
最後回到那個共用的 _ticketNum:三套 API 都不會幫你解決資料競爭。若要寫得既安全又乾淨,可以改用 GCD 的串行佇列當作鎖:
dispatch_queue_t ticketQueue = dispatch_queue_create("com.example.ticket", DISPATCH_QUEUE_SERIAL);
dispatch_async(ticketQueue, ^{
if (_ticketNum > 0) {
_ticketNum--;
}
});
這比 NSLock 更可讀,也能保證操作順序,是 Apple 官方偏好的做法之一。