您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 技巧大全

iOS 多線程入門:NSOperation、NSOperationQueue 與 NSThread 鎖機制

編輯:iOS 技巧大全

iOS 上的執行緒不是無限資源。官方資料指出,主執行緒的堆疊大小約為 1M,第二條之後的執行緒則是 512KB,而且這個值無法透過編譯器參數或執行緒 API 更改。另一個關鍵限制是:只有主執行緒能直接操作 UI。

一、NSOperation 與 NSOperationQueue

  1. 自訂的操作類別必須繼承 NSOperation,並實作 - (void)main。
  2. 使用 NSOperation 最簡單的方式,就是把它放進 NSOperationQueue。一旦入列,佇列會啟動並呼叫該操作的 main,完成後自動釋放。
self.queue = [[NSOperationQueue alloc] init];
ArticleParseOperation *parser = [[ArticleParseOperation alloc] initWithData:filePath delegate:self];
[queue addOperation:parser];
[parser release];
[queue release];

// 限制同時執行的最大操作數
[queue setMaxConcurrentOperationCount:2];

二、NSThread 建立與啟動

建立執行緒主要有兩種指定初始化器的方式:

- (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)這套更現代的方案。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved