iOS 上的執行緒不是無限資源。官方資料指出,主執行緒的堆疊大小約為 1M,第二條之後的執行緒則是 512KB,而且這個值無法透過編譯器參數或執行緒 API 更改。另一個關鍵限制是:只有主執行緒能直接操作 UI。
- (void)main。self.queue = [[NSOperationQueue alloc] init]; ArticleParseOperation *parser = [[ArticleParseOperation alloc] initWithData:filePath delegate:self]; [queue addOperation:parser]; [parser release]; [queue release]; // 限制同時執行的最大操作數 [queue setMaxConcurrentOperationCount:2];
建立執行緒主要有兩種指定初始化器的方式:
- (id)init; - (id)initWithTarget:(id)target selector:(SEL)selector object:(id)argument;
另外還有一個更方便的寫法,會直接建立並啟動執行緒,而且不必負責清理:
+ (void)detachNewThreadSelector:(SEL)aSelector toTarget:(id)aTarget withObject:(id)anArgument
前兩種方式建立後,需要自行呼叫 - (void)start; 才會啟動。
說明同步與鎖,最經典的例子就是多視窗售票。Java 用 synchronized,Objective-C 沒有同名關鍵字,但提供了 NSCondition 這個鎖物件,可以達到同樣效果。
SellTicketsAppDelegate.h:
@interface SellTicketsAppDelegate : NSObject <UIApplicationDelegate> {
int tickets;
int count;
NSThread *ticketsThreadone;
NSThread *ticketsThreadtwo;
NSCondition *ticketsCondition;
UIWindow *window;
}
@property (nonatomic, retain) IBOutlet UIWindow *window;
@end
SellTicketsAppDelegate.m:
- (void)applicationDidFinishLaunching:(UIApplication *)application {
tickets = 100;
count = 0;
ticketsCondition = [[NSCondition alloc] init];
ticketsThreadone = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
[ticketsThreadone setName:@"Thread-1"];
[ticketsThreadone start];
ticketsThreadtwo = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
[ticketsThreadtwo setName:@"Thread-2"];
[ticketsThreadtwo start];
[window makeKeyAndVisible];
}
- (void)run {
while (TRUE) {
[ticketsCondition lock]; // 上鎖
if (tickets > 0) {
[NSThread sleepForTimeInterval:0.5];
count = 100 - tickets;
NSLog(@"當前票數是:%d, 售出:%d, 線程名:%@", tickets, count, [[NSThread currentThread] name]);
tickets--;
} else {
[ticketsCondition unlock];
break;
}
[ticketsCondition unlock]; // 解鎖
}
}
少了 lock/unlock 這一層,兩個執行緒就可能賣出同一張票,這就是所謂的「髒資料」。
背景執行緒算完東西後,要回到主執行緒更新 UI,用這個介面:
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)object waitUntilDone:(BOOL)wait
另外,背景任務記得包在 NSAutoreleasePool 裡,否則會出現 NSAutoReleaseNoPool(): Object ... autoreleased with no pool in place 這類錯誤:
- (void)startTheBackgroundJob {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// 執行背景工作...
[self performSelectorOnMainThread:@selector(makeMyProgressBarMoving)
withObject:nil waitUntilDone:NO];
[pool release];
}
若想更進一步管理執行緒生命週期與併發數量,可以研究 NSOperation 與 NSOperationQueue 的相關 API,或是直接採用 GCD(dispatch_queue、dispatch_group、dispatch_once)這套更現代的方案。