GCD 入門

同步,異步:
同步是指:當一個 block 被添加到 queue 時,會阻塞當前運行的線程,直到 block 中的內容執行完畢,異步則不會阻塞當前的線程
串行,并行:
串行,同一時間下只有一個任務被執行,并行則可以有多個任務同時執行

同步異步決定開不開線程,串行并行決定開幾條線程
代碼中都有注釋,很容易理解:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self asyncGlobalQueue];
}

     /// 同步不開辟線程,異步開啟新線程
     /// 串行只開辟一條線程,并行開啟多條線程

     /// 同步+ mainQueue 死鎖
      /// 主線程先添加 dispatch_sync操作到 mainQueue,sync 使主線程陷
    入等待dispatch_sync的 block 執行結束,
     /// dispatch_sync又添加 block 到 mainQueue, 該 block 只有結束后 
     dispatch_sync 才能完全結束,此刻mainQueue 中有兩個操作
    /// 1. dispatch_sync 2.block dispatch 等待 block 結束, block 等待 
    dispatch_sync 結束, block 無法執行
    /// 死鎖
   - (void)syncMainQueue
  {
    dispatch_sync(dispatch_get_main_queue(), ^{
       NSLog(@"%@",[NSThread currentThread]);
   });
    NSLog(@"method end");
  }

   /// 同步 + 串行隊列
   - (void)syncSerialQueue
  {
     // 第一個參數: 表示隊列名
     // 第二個參數: NULL:創建串行隊列, DISPATCH_QUEUE_CONCURRENT
      并發隊列
dispatch_queue_t sprialQueue = dispatch_queue_create("com.X-Liang", NULL);
dispatch_async(sprialQueue, ^{
    NSLog(@"%@",[NSThread currentThread]);
    dispatch_sync(sprialQueue, ^{
        /// 此線程中sprialQueue 中有兩個操作 dispatch_sync, block, block 等待 dispatch_sync, dispacth_sync 等待
        /// block 執行,導致該線程死鎖, block 無法執行
        NSLog(@"Hello");    // 無法執行
    });
});
}

   /// 同步 + 并行隊列
   - (void)syncConcurrentQueue
  {
/// dispatch_sync 任務被添加到 MainQueue 中, block 被添加到 global_queue 中
/// 又因為為同步添加 block ,所以 MainQueue 會等待 global_queu 中的 block 任務執行完畢后,才繼續執行
/// 2015-07-05 13:15:39.163 GCD[7372:349190] <NSThread: 0x7fd021411720>{number = 1, name = main}
/// 2015-07-05 13:15:39.163 GCD[7372:349190] method end
dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    NSLog(@"%@",[NSThread currentThread]);
});
NSLog(@"method end");
 }

/// 異步 + 串行
- (void)asyncSerialQueue
{
dispatch_queue_t serialQueue = dispatch_queue_create("com.X-Liang", NULL);
dispatch_async(serialQueue, ^{
NSLog(@"%@",[NSThread currentThread]);
});
}

    /// 異步 + 并行
    /**
      * 異步函數+并發隊列
      * 利用異步函數,往并發隊列中添加任務,會開辟與隊列中任務數相同的線程
      */
    - (void)asyncGlobalQueue
   {
     // 1. 獲得全局并發隊列
     /**
       * 第一個參數設置隊列的優先級
       * 第二個參數設置一個標志,設置為0
       */
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

// 異步(具備開辟線程能力)并發執行
dispatch_async(queue, ^{
    NSLog(@"%@",[NSThread currentThread]);
    for (int index = 0; index < 100; ++index) {
        NSLog(@"A");
    }
    
});

dispatch_async(queue, ^{
    NSLog(@"%@",[NSThread currentThread]);
    for (int index = 0; index < 100; ++index) {
        NSLog(@"B");
    }
    
});

dispatch_async(queue, ^{
    NSLog(@"%@",[NSThread currentThread]);
    for (int index = 0; index < 100; ++index) {
        NSLog(@"B");
    }
    
});
}

有錯請指正,謝謝,共同學習進步

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

推薦閱讀更多精彩內容