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

iOS 多線程全景:從 pthread 到 GCD 與 NSOperation

編輯:iOS 技巧大全

一、基本概念

進程是系統中正在運行的應用程序,各進程相互獨立,各自運行在專用且受保護的內存空間。線程則是進程的基本執行單元,一個進程至少有一條線程,進程內的所有任務都在線程中完成。

同一條線程內的任務是串行的,同一時刻只能做一件事。多線程指一個進程內開啟多條線程,讓不同任務並行推進,例如同時下載三個文件。

嚴格說,單核環境下「並行」是一種效果:CPU 在多條線程間高速切換調度,快到讓人產生同時執行的錯覺。

取捨很清楚。優點是提高執行效率與 CPU、內存利用率;缺點是每條線程都要佔用棧空間(主線程約 1M,子線程約 512KB),線程越多調度開銷越大,並且線程通信與數據共享會讓設計複雜度上升。

iOS 程序啟動後默認有一條主線程(UI 線程),負責刷新界面與處理 UI 事件。因此有兩條鐵律:耗時操作不要放在主線程,會卡住界面;所有 UI 更新必須回到主線程執行。

二、四種實現方案

1. pthread

最底層的 C 語言 API,需要手動管理線程對象與函數指針。

#include <pthread.h>
pthread_t thread;
NSString *name = @"線程";
// 參數依次為:線程對象地址、線程屬性、函數指針、傳入參數
pthread_create(&thread, NULL, run, (__bridge void *)(name));

2. NSThread

Objective-C 封裝,三種啟動方式各有側重:

// 方式一:alloc init,需手動 start,可拿到線程對象做細節設置
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run:) object:@"線程"];
[thread start];

// 方式二:detach 分離出新線程,自動啟動但無法細調
[NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:@"分離出的子線程"];

// 方式三:後台線程,自動啟動,同樣不能細調
[self performSelectorInBackground:@selector(run:) withObject:@"後台線程"];

常用屬性與狀態控制:

thread.name = @"線程A";
thread.threadPriority = 1.0;   // 取值 0.0 ~ 1.0,默認 0.5

[NSThread exit];                                            // 退出當前線程
[NSThread sleepForTimeInterval:2.0];                        // 阻塞指定時長
[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:2.0]]; // 阻塞到指定時刻
// 注意:線程一旦結束無法復活

線程安全方面,多線程訪問同一塊資源會出現數據競爭,方案是加互斥鎖:

@synchronized (self) {
    // 同一時間只有一個線程能進入
}
// 原子性(atomic)本質就是給 setter 加鎖,非原子則不加

線程間通信的典型場景是子線程下載、主線程刷新:

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [NSThread detachNewThreadSelector:@selector(downloadImage) toTarget:self withObject:nil];
}

- (void)downloadImage {
    NSURL *url = [NSURL URLWithString:@"https://example.com/a.jpg"];
    NSData *data = [NSData dataWithContentsOfURL:url];
    UIImage *image = [UIImage imageWithData:data];

    // 三種回到主線程的方式
    [self performSelectorOnMainThread:@selector(showImage:) withObject:image waitUntilDone:YES];
    [self.imageView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:YES];
    [self.imageView performSelector:@selector(setImage:) onThread:[NSThread mainThread] withObject:image waitUntilDone:YES];
}

代碼耗時統計:

NSDate *start = [NSDate date];
NSData *data = [NSData dataWithContentsOfURL:url];
NSDate *end = [NSDate date];
NSLog(@"耗時 %f 秒", [end timeIntervalSinceDate:start]);

// 或者用更精確的絕對時間
CFTimeInterval t1 = CFAbsoluteTimeGetCurrent();
NSData *data2 = [NSData dataWithContentsOfURL:url];
CFTimeInterval t2 = CFAbsoluteTimeGetCurrent();
NSLog(@"耗時 %f 秒", t2 - t1);

3. GCD

兩個核心概念:隊列與任務;兩類提交方式:同步與異步。它是 C 接口,但比 pthread 好用得多。

線程間通信:

// 取全局並發隊列
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
dispatch_async(queue, ^{
    NSURL *url = [NSURL URLWithString:@"https://example.com/b.jpg"];
    NSData *data = [NSData dataWithContentsOfURL:url];
    UIImage *image = [UIImage imageWithData:data];
    NSLog(@"下載線程 -- %@", [NSThread currentThread]);

    // 回主線程刷新 UI
    dispatch_async(dispatch_get_main_queue(), ^{
        self.imageView.image = image;
        NSLog(@"刷新 UI -- %@", [NSThread currentThread]);
    });
});

其他高頻 API:

// 柵欄函數:等待前面的任務完成後單獨執行,用於讀寫保護
dispatch_barrier_async(queue, ^{ NSLog(@"barrier"); });

// 延遲執行
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)),
               dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    NSLog(@"--- %@", [NSThread currentThread]);
});

// 只執行一次,常用於單例(不要放進懶加載)
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{ NSLog(@"once"); });

// 快速迭代,多線程並發完成遍歷
dispatch_apply(subpaths.count, queue, ^(size_t index) { });

// 隊列組:組內任務全部完成後再執行指定 block
dispatch_group_t group = dispatch_group_create();
dispatch_group_notify(group, queue, ^{ NSLog(@"全部完成"); });

4. NSOperation

NSOperation 是蘋果對 GCD 的面向對象包裝,核心概念是「隊列 + 操作」。它是抽象類,實踐中用三個子類:NSInvocationOperation、NSBlockOperation,以及繼承 NSOperation 自定義。

// 方式一:NSInvocationOperation
NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self
                                                               selector:@selector(run)
                                                                 object:nil];
[op start];

// 方式二:NSBlockOperation,可追加多個 block
NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{ NSLog(@"download1"); }];
[op2 addExecutionBlock:^{ NSLog(@"download2"); }];
[op2 addExecutionBlock:^{ NSLog(@"download3"); }];
[op2 start];

// 方式三:自定義,重寫 main
@implementation ZCOperation
- (void)main {
    NSLog(@"-- main -- %@", [NSThread currentThread]);
}
@end
ZCOperation *op3 = [[ZCOperation alloc] init];
[op3 start];

三、NSOperationQueue

隊列分兩種:[NSOperationQueue mainQueue] 裡的任務一定在主線程執行;自己 alloc 出來的隊列默認並發,通過最大並發數屬性可切換成串行。

NSOperationQueue *queue = [[NSOperationQueue alloc] init];

// 最大並發數,需在添加操作之前設置
// 等於 1 時隊列變串行,大於 1 為並行,-1 表示由系統決定
queue.maxConcurrentOperationCount = 2;

// 暫停 / 恢復:暫停只是不再啟動下一個操作,可恢復
queue.suspended = queue.isSuspended ? NO : YES;

// 取消隊列中所有操作,不可恢復
[queue cancelAllOperations];

自定義操作中響應取消,是提升性能的好習慣——每完成一段耗時工作就檢查一次:

- (void)main {
    for (int i = 0; i < 1000; i++) {
        NSLog(@"任務1-%d", i);
    }
    // 蘋果官方建議:耗時操作之間檢查取消狀態
    if (self.isCancelled) { return; }
    for (int i = 0; i < 1000; i++) {
        NSLog(@"任務2-%d", i);
    }
}

操作依賴可以表達執行順序,例如先下載兩張圖再合成:

- (void)download2 {
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];

    NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{
        NSURL *url = [NSURL URLWithString:@"https://example.com/1.jpg"];
        self.image1 = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
    }];
    NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{
        NSURL *url = [NSURL URLWithString:@"https://example.com/2.jpg"];
        self.image2 = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
    }];
    NSBlockOperation *combine = [NSBlockOperation blockOperationWithBlock:^{
        UIGraphicsBeginImageContext(CGSizeMake(200, 200));
        [self.image1 drawInRect:CGRectMake(0, 0, 200, 100)];
        [self.image2 drawInRect:CGRectMake(0, 100, 200, 100)];
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            self.imageView.image = image;
        }];
    }];

    // 合成操作依賴兩個下載操作
    [combine addDependency:op1];
    [combine addDependency:op2];

    [queue addOperation:op1];
    [queue addOperation:op2];
    [queue addOperation:combine];
}

四、補充:自建隊列與全局隊列的區別

1)全局並發隊列由系統預先創建,共有高、默認、低、後台四個優先級,我們只是取來用;dispatch_queue_create 則是真正新建一個隊列。
2)iOS 6.0 之前,用 create、retain 創建的隊列需要手動 release,主隊列與全局隊列不需要;6.0 之後 GCD 已納入 ARC 管理,不必再手動釋放。
3)柵欄函數只有與自己創建的並發隊列搭配使用才生效,這是蘋果明確規定的。
4)更多差異涉及 XNU 內核的系統級線程編程,此處不再展開。有興趣可查閱 GCD 官方 API 文檔與 libdispatch 源碼。

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