讀書筆記 多線程 -- NSThread

NSThread 是傳統意義上底層pthread線程的OC封裝
優點:

  • 設置線程的服務質量Qos
  • 可以設置線程堆大小
  • 線程提供local數據字典,可以存儲key/value數據
  • 實時性更高
  • 與RunLoop結合,提供更為靈活高效的線程管理方式

缺點:

  • 創建線程代時,需要同時占用應用和內核的內存空間(GCD只占用內核的內存空間)
  • 編寫線程相關代碼相對繁雜

1.線程的創建方式

    // 1.
    [NSThread detachNewThreadWithBlock:^{
        NSLog(@"NSThread");
    }];
    // 2.
    [NSThread detachNewThreadSelector:@selector(dosomething:) toTarget:self withObject:data];
    // 3.
    NSThread * thread = [[NSThread alloc]initWithTarget:self selector:@selector(dosomething:) object:data];
    thread.name = @"thread1";
    [thread start];
// 4. 子類化NSThread
// 重載main方法實現子類化,加上自動釋放池確保線程處理過程中及時釋放內存資源。
- (void)main{
    @autoreleasepool {
        // 線程處理
    }
}

2.NSTread類的屬性和方法

// 獲取當前線程
@property (class, readonly, strong) NSThread *currentThread;
// 是否支持多線程
+ (BOOL)isMultiThreaded;
//  線程本地的數據字典
@property (readonly, retain) NSMutableDictionary *threadDictionary;
// 休眠到指定的日期
+ (void)sleepUntilDate:(NSDate *)date;
// 定期休眠
+ (void)sleepForTimeInterval:(NSTimeInterval)ti;
// 退出線程
+ (void)exit;
// 線程的優先級
+ (double)threadPriority;
// 設置線程的優先級
+ (BOOL)setThreadPriority:(double)p;
// 線程服務質量
@property NSQualityOfService qualityOfService ; // read-only after the thread is started
// 堆棧返回地址
@property (class, readonly, copy) NSArray<NSNumber *> *callStackReturnAddresses ;
// 堆棧調用鏈
@property (class, readonly, copy) NSArray<NSString *> *callStackSymbols ;
// 線程的名字
@property (nullable, copy) NSString *name ;
// 堆棧的大小
@property NSUInteger stackSize ;
// 是否是主線程
@property (readonly) BOOL isMainThread ;
@property (class, readonly, strong) NSThread *mainThread;
// 是否正在執行
@property (readonly, getter=isExecuting) BOOL executing ;
// 是否已完成
@property (readonly, getter=isFinished) BOOL finished ;
// 是否取消
@property (readonly, getter=isCancelled) BOOL cancelled ;
// 取消執行
- (void)cancel ;
// 開始執行
- (void)start;
// 線程執行的主方法,子類化線程時需要 重載這個方法
- (void)main;   // thread body method

3.NSObject線程擴展方法

// 在主線程執行方法
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(nullable id)arg waitUntilDone:(BOOL)wait modes:(nullable NSArray<NSString *> *)array;
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(nullable id)arg waitUntilDone:(BOOL)wait;
    // equivalent to the first method with kCFRunLoopCommonModes
// 在指定線程 執行方法
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(nullable id)arg waitUntilDone:(BOOL)wait modes:(nullable NSArray<NSString *> *)array API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(nullable id)arg waitUntilDone:(BOOL)wait API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));
// 后臺線程執行方法
- (void)performSelectorInBackground:(SEL)aSelector withObject:(nullable id)arg API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));

4.線程中的共享資源保護

4.1. OSAtomic 原子操作 更輕量級,性能更高。
4.2.加鎖

(1)NSLock 互斥鎖

    NSLock * theLock = [[NSLock alloc]init];
    if ([theLock tryLock]) {// 嘗試獲取鎖,不會阻塞當前任務的執行
        NSLog(@"讀寫");
        [theLock unlock];
    }

(2)NSRecursiveLock 遞歸鎖
主要用在 循環或者遞歸操作中,保證同一個線程執行多次加鎖操作不會產生死鎖,只要保證加鎖和解鎖的次數相同,就能釋放資源使其他線程得到資源使用。

    NSRecursiveLock * recursive = [[NSRecursiveLock alloc]init];
    for (int i = 0; i < 10; i ++) {
        [recursive lock];
        NSLog(@"讀寫操作");
        [recursive unlock];
    }

(3)NSConditionLock條件鎖

condition為一個整數參數
當condition的值滿足時 可以獲得鎖;
解鎖時可以設置condition條件;

lockWhenCondition:表示condition為參數值時 獲得鎖
unlockWithCondition: 表示解鎖并設置condition的值

4.3. NSCondition

通過一些條件控制多線程執行任務,當條件不滿足時線程等待;條件滿足時通過發送signal信號等待線程 繼續處理

    NSCondition * condition = [[NSCondition alloc]init];
    [condition lock];
    if (0) {
        // 如果條件不滿足 等待
        [condition wait];
    }else{
        // 條件滿足,發送信號
        [condition signal];
    }
    [condition unlock];
4.4.@synchronized 同步指令

synchronized是自動實現加鎖技術的,同時增加了異常處理。
編譯器自動插入加鎖和解鎖的代碼,同時捕獲異常避免異常時不能及時釋放鎖,導致死鎖。

@synchronized (self){
 // do something
}

來自 《macOS應用開發基礎教程 張帆》讀書筆記

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。