在 Objective-C 開發中,並發並不是單一技術,而是多層次的工具選擇。本文以三個常見方案為主線:原生線程、Operation 與 Operation Queue、Grand Central Dispatch,說明各自的使用時機與實作重點。
若只是想把某個方法放到背景執行,可以直接使用 performSelectorInBackground:withObject:。這種方式會立刻建立一條新的背景線程,而目前的主線程不會被阻塞。
ConcurrentProcessor *processor = [ConcurrentProcessor new];
[processor performSelectorInBackground:@selector(computeTask:) withObject:@5];
[processor performSelectorInBackground:@selector(computeTask:) withObject:@10];
[processor performSelectorInBackground:@selector(computeTask:) withObject:@20];
while (!processor.isFinished) {
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
}
NSLog(@"Computation result = %ld", processor.computeResult);
在背景線程中,建議自行建立 @autoreleasepool,並視情況加入例外處理。若多個線程會同時修改同一份資料,就必須使用鎖、@synchronized 或其他同步機制避免資料競爭。
如果需要更精細地控制線程,例如設定優先權、手動啟動,可以使用 NSThread。
NSThread *computeThread = [[NSThread alloc] initWithTarget:processor
selector:@selector(computeTask:)
object:@20];
computeThread.threadPriority = 0.5;
[computeThread start];
也可以使用更方便的寫法,直接建立並啟動背景線程:
[NSThread detachNewThreadSelector:@selector(computeTask:)
toTarget:processor
withObject:@10];
NSOperation 適合把一個任務封裝成物件。若只是非並發任務,通常只需要重寫 main 方法;若要做成並發操作,則需要處理 start、isConcurrent、isExecuting、isFinished 等狀態,並在狀態改變時送出適當的 KVO 通知。
@implementation GreetingOperation
- (void)main {
@autoreleasepool {
NSLog(@"Hello, World");
[NSThread sleepForTimeInterval:3.0];
NSLog(@"Goodbye, World");
}
}
@end
如果希望操作以並發方式執行,可以在子類中實作:
- (BOOL)isConcurrent {
return YES;
}
- (BOOL)isExecuting {
return executing;
}
- (BOOL)isFinished {
return finished;
}
NSOperationQueue 可以管理多個 NSOperation,並且支援相依性設定。例如可以要求某個操作必須在另一個操作完成後才能執行。
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
ConcurrentProcessor *proc1 = [[ConcurrentProcessor alloc] initWithData:resultPointer computations:5];
ConcurrentProcessor *proc2 = [[ConcurrentProcessor alloc] initWithData:resultPointer computations:10];
ConcurrentProcessor *proc3 = [[ConcurrentProcessor alloc] initWithData:resultPointer computations:20];
[proc2 addDependency:proc1];
[queue addOperations:@[proc1, proc2, proc3] waitUntilFinished:NO];
[queue waitUntilAllOperationsAreFinished];
在上述例子中,proc1 與 proc3 可以並行執行,但 proc2 必須等待 proc1 完成。
Grand Central Dispatch 是 Apple 提供的輕量級並發工具。它不需要建立額外的類別,只要把任務交給序列隊列或群組即可。
dispatch_queue_t serialQueue = dispatch_queue_create("MySerialQueue", DISPATCH_QUEUE_SERIAL);
dispatch_queue_t serialQueue2 = dispatch_queue_create("MySerialQueue2", DISPATCH_QUEUE_SERIAL);
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, serialQueue, ^{
NSLog(@"Task 1");
});
dispatch_group_async(group, serialQueue2, ^{
NSLog(@"Task 2");
});
dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
同一個序列隊列中的任務會依序執行,不同序列隊列之間則可以並行。若需要等待整批任務完成,可以使用 dispatch_group_wait 或 dispatch_group_notify。
在一般 iOS 開發中,若沒有特殊即時性需求,通常會優先考慮 Operation Queue 或 GCD。若需要處理即時約束或特殊系統任務,原生線程仍然有其價值。