GCD NSOperation 拾遺

  1. 并發(fā) vs 并行

    1. 并發(fā): 一段時(shí)間內(nèi)存在多個(gè)執(zhí)行路徑,單核cpu,分時(shí)執(zhí)行
    2. 并發(fā): 同一時(shí)刻,存在多個(gè)執(zhí)行路徑的任務(wù)
  2. 同步 vs 異步

    1. 同步,阻塞當(dāng)前隊(duì)列的執(zhí)行,執(zhí)行完畢之后,進(jìn)行執(zhí)行
    2. 異步,只是添加block到隊(duì)列中去,并不等待執(zhí)行
  3. 串行 vs 并行

    1. 串行 FIFO的執(zhí)行順序
    2. 并行 任務(wù)提交按FIFO,任務(wù)的執(zhí)行不是
  4. NSBlockOperation vs NSInvocationOperation

    1. BlockOperation, 并發(fā)操作, 可以捕獲更多的 參數(shù),同時(shí)可以添加 多個(gè)block
    2. InvocationOperation ,串行操作,對(duì)已有的方法,直接設(shè)定會(huì)比較合適
  5. NSOperation 是如何執(zhí)行的?

    1. operation 先check 依賴關(guān)系,如果有,先完成依賴操作,如果沒(méi)有,開(kāi)始執(zhí)行
    2. 如果并發(fā)設(shè)置為1,則FIFO隊(duì)列順序執(zhí)行,有優(yōu)先級(jí)排序的設(shè)定
    3. 否則將并行執(zhí)行,多個(gè)操作
    4. operation 執(zhí)行的影響因素有3個(gè),添加到queue 的順序,依賴關(guān)系,它所在隊(duì)列的優(yōu)先級(jí)
  6. 主隊(duì)列能否修改并發(fā)數(shù)?

    1. 不能,及時(shí)你修改了,也是無(wú)效的。
  7. GCD 是否一定開(kāi)辟新線程?

    1. 線程池循環(huán)使用
  8. dispatch_once 如何實(shí)現(xiàn)的?

  9. 信號(hào)量控制并發(fā)數(shù) dispatch_semaphore

    // 創(chuàng)建隊(duì)列組
    dispatch_group_t group = dispatch_group_create();
    // 創(chuàng)建信號(hào)量,并且設(shè)置值為3
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(3);
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    for (int i = 0; i < 100; i++)
    {
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        dispatch_group_async(group, queue, ^{
            NSLog(@"%i",i);
            sleep(2);
            // 每次發(fā)送信號(hào)則semaphore會(huì)+1,
            dispatch_semaphore_signal(semaphore);
        });
    }
    
  10. 多線程是為了解決什么問(wèn)題而引入的概念?

  11. 什么情況下你會(huì)使用多線程?對(duì)于一個(gè)可分治的問(wèn)題規(guī)模為 n 的任務(wù),多線程和單線程兩種方式哪個(gè)能更快完成任務(wù)?

  12. NSOperation 是為了解決什么問(wèn)題而引入的?

  13. GCD 是為了解決什么問(wèn)題而引入的?什么時(shí)候你會(huì)用 NSThread?什么時(shí)候你會(huì)用 NSOperation?什么時(shí)候你會(huì)用 GCD?

  14. 隊(duì)列 vs 線程的區(qū)別

    let key = DispatchSpecificKey<String>()
    DispatchQueue.main.setSpecific(key: key, value: "main")
    func log() {
        debugPrint("main thread: \(Thread.isMainThread)")
        let value = DispatchQueue.getSpecific(key: key)
        debugPrint("main queue: \(String(describing: value)) \(value != nil)")
    }
    DispatchQueue.global().sync(execute: log)
    
      // "main thread: true"
        //"main queue: nil false"
        // 結(jié)論:隊(duì)列是對(duì)執(zhí)行item 的管理,線程是真正的執(zhí)行體
    
  15. GCD NSOperation 比較

    • GCD是純C語(yǔ)言的API,NSOPerationQueue是基于GCD的OC版本的封裝;

    • GCD只支持FIFO的隊(duì)列,NSOPerationQueue可以很方便的調(diào)整執(zhí)行順序、設(shè)置最大并發(fā)數(shù)量;

    • NSOPerationQueue可以輕松在Operation間設(shè)置依賴關(guān)系,而GCD需要寫(xiě)很多的代碼才能實(shí)現(xiàn);

    • NSOperationQueue支持KVO,可以檢測(cè)operation是否正在執(zhí)行(isExecuted)、是否結(jié)束(isFinished)、是否取消(isCanceled);

    • GCD的執(zhí)行速度比NSOperationQueue快

      適用范圍:

      • 任務(wù)之間不太相互依賴:GCD
      • 任務(wù)之間有依賴或者要監(jiān)聽(tīng)任務(wù)的執(zhí)行情況:NSOperationQueue
    NSLog(@"0 %@", NSThread.currentThread);

    NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"1 %@", NSThread.currentThread);
    }];
    
    for (int i=2; i<50; i++) {
        [operation addExecutionBlock:^{
            NSLog(@"%d %@", i, NSThread.currentThread);
        }];
    }
    
    NSLog(@"5.0 %@", NSThread.currentThread);

    operation.completionBlock = ^{
        NSLog(@"finished %@", NSThread.currentThread);
    };
    NSLog(@"5.1 %@", NSThread.currentThread);
    [[NSOperationQueue mainQueue] addOperation:operation];
    NSLog(@"6 %@", NSThread.currentThread);

上面的代碼總結(jié),block operation 的執(zhí)行隊(duì)列,有系統(tǒng)分配,它是并行操作,main queue add operation , 只是 queue 調(diào)用了 operation 的start 方法。

GCD vs NSOperation

GCD is a low-level C-based API.
NSOperation and NSOperationQueue are Objective-C classes.
NSOperationQueue is objective C wrapper over GCD. If you are using NSOperation, then you are implicitly using Grand Central Dispatch.

GCD advantage over NSOperation:
i. implementation
For GCD implementation is very light-weight
NSOperationQueue is complex and heavy-weight

NSOperation advantages over GCD:

i. Control On Operation
you can Pause, Cancel, Resume an NSOperation

ii. Dependencies
you can set up a dependency between two NSOperations
operation will not started until all of its dependencies return true for finished.

iii. State of Operation
can monitor the state of an operation or operation queue. ready ,executing or finished

iv. Max Number of Operation
you can specify the maximum number of queued operations that can run simultaneously

When to Go for GCD or NSOperation
when you want more control over queue (all above mentioned) use NSOperation and for simple cases where you want less overhead (you just want to do some work "into the background" with very little additional work) use `GCD

gcd operation thread
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容