【iOS開發】多執行緒 - 概述

weixin_34320159發表於2017-09-21
  • 執行緒
    • 主執行緒
    • 後臺執行緒

  • 執行緒是被模擬出來的,CPU通過分配時間片的方法模擬出多執行緒


    752708-3c22543dff88ea57.jpg
    CPU通過分配時間片的方法模擬出多執行緒

  • NSThread建立一個執行緒

    • 物件方法
      // 物件方法
      NSThread *thread1 = [[NSThread alloc] initWithBlock:^{
          ...
      }];
      [thread1 start];
    
    • 類方法
      // 類方法
      [NSThread detachNewThreadWithBlock:^{
          ...
      }];
    
    • 繼承物件
      @interface testThread : NSThread
    
      @end
    
      @implementation testThread
    
      - (void)main {
          ...
      }
    
      @end
    
      // 繼承方法
      testThread *thread_t = [[testThread alloc] init];
      thread_t.delegate = self;
      [thread_t start];
    

  • 執行緒的狀態


    752708-5cc6e2388ada2234.jpg
    執行緒的狀態
  • 優雅的取消一個執行緒

// way1,該執行緒立刻退出,若果該執行緒退出前執行緒中申請的資源沒有釋放容易造成記憶體洩漏
+ (void)exit
// way2,不作特殊處理該執行緒會繼續執行
- (void)cancel
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    _thread1 = [[NSThread alloc] initWithBlock:^{
        NSLog(@"thread start");
        for (NSInteger i = 0; i <= 100; i ++) {
            NSLog(@"%@ --- %ld", _thread1, (long)i);
            sleep(1);
            if ([[NSThread currentThread] isCancelled]) {
                break;
            }
        }
        NSLog(@"thread end");
    }];
    [_thread1 start];
}

#pragma mark - Button methods

- (IBAction)handleCancelThread:(id)sender {
    [_thread1 cancel];
    _thread1 = nil;
}
752708-9a53bf0ff2817812.jpg

  • 執行緒相關的方法
+ (BOOL)isMainThread; // 當前的程式碼執行的執行緒是否是主執行緒
+ (NSThread *)currentThread; // 當前程式碼執行的執行緒
+ (NSThread *)mainThread; // 獲取主執行緒
  • 暫停執行緒的方法
+ (void)sleepUntilDate:(NSDate *)date;
+ (void)sleepForTimeInterval:(NSTimeInterval)ti;
  • 執行緒通訊
@interface NSObject (NSThreadPerformAdditions)
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(nullable id)arg waitUntilDone:(BOOL)wait;
- (void)performSelectorInBackground:(SEL)aSelector withObject:(nullable id)arg
@end

  • 多執行緒優點

    • 提高APP實時響應效能
    • 充分利用計算資源
  • 多執行緒缺點

    • 執行緒安全
    • 複雜度提升
    • 需要額外的系統開銷

  • 執行緒的開銷
752708-53784d3cb6eafbfc.jpg
執行緒開銷
  • 執行緒同步問題


    752708-dcc92cf27da5972d.jpg
  • 執行緒同步的方法

    • NSLock
    @protocol NSLocking
    // 訪問變數前後使用
    - (void)lock;
    - (void)unlock;
    
    @end
    
    @interface NSLock : NSObject <NSLocking> {
    @private
        void *_priv;
    }
    
    - (BOOL)tryLock;
    - (BOOL)lockBeforeDate:(NSDate *)limit;
    
    @property (nullable, copy) NSString *name API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0),   tvos(9.0));
    
    @end
    
    • synchronized
    @synchronized (self) {
          a ++;
    }
    

  • 死鎖


    752708-cea7fd1e4bde8f7e.jpg

相關文章