GCD Group、Barrier、Semaphore、NSOperationQueue使用

先貼上打印函數:

- (void)p_printThread:(int)index {
    NSLog(@"%@-------%d", [NSThread currentThread], index);
}

1. Group

Group作用:在并發異步隊列中,等待執行一系列任務后,再執行一個任務。實現方式有兩種:notify和wait。
notify示例代碼:

dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_async(group, concurrentQueue, ^{ 
        [self p_printThread:1];
    });
    dispatch_group_async(group, concurrentQueue, ^{ 
        [self p_printThread:2];
    });
    dispatch_group_async(group, concurrentQueue, ^{
        [self p_printThread:3];
    });
    dispatch_group_async(group, concurrentQueue, ^{ 
        [self p_printThread:4];
    });
    // 使用dispatch_group_wait,可以阻塞線程,等待group的任務執行完畢,才能繼續執行后續任務
    // 使用dispatch_group_notify,不會阻塞線程(group外的線程執行順序不受影響),而且可以在執行完成group的任務后進行操作
    dispatch_group_notify(group, concurrentQueue, ^{
        [self p_printThread:0];
    });

打印結果:

<NSThread: 0x610000260d80>{number = 4, name = (null)}-------2
<NSThread: 0x608000261400>{number = 5, name = (null)}-------3
<NSThread: 0x618000264f40>{number = 3, name = (null)}-------1
<NSThread: 0x610000260e40>{number = 6, name = (null)}-------4
<NSThread: 0x610000260e40>{number = 6, name = (null)}-------0

wait示例代碼:

dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_group_t group = dispatch_group_create();
    for (int i=0; i<4; i++)  {
        dispatch_group_enter(group);
        dispatch_async(concurrentQueue, ^{
            [self p_printThread:i+1];
        });   
        dispatch_group_leave(group);
    }
    // 使用dispatch_group_wait,可以阻塞線程,等待group的任務執行完畢
    dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
    dispatch_async(dispatch_get_main_queue(), ^{
        // 主線程處理
        [self p_printThread:0];
    });

打印結果:

<NSThread: 0x600000076600>{number = 4, name = (null)}-------2
<NSThread: 0x600000076740>{number = 6, name = (null)}-------4
<NSThread: 0x610000073280>{number = 3, name = (null)}-------1
<NSThread: 0x608000076380>{number = 5, name = (null)}-------3
<NSThread: 0x60000007b240>{number = 1, name = main}-------0

結論:運行多次,任務1、2、3、4的順序不定,但任務0總是最后一個。應用場景:單界面多請求完成后,主線程刷新界面;notify和wait的區別:wait會阻塞線程,notify不會阻塞線程,較好一點

2. Barrier

Barrier作用:Barrier在并發異步隊列中起到承上啟下的作用(Barrier就像名字一樣,類似一個柵欄把前后的任務隔開了)。Barrier前后任務執行順序為:Barrier前面的線程(多個的話,仍是并行)--->barrier線程--->barrier后面的線程(多個的話,仍是并行)。需要注意的是:Barrier在全局并發隊列不起作用,只有在自己創建的并發隊列才起作用。

示例代碼:

// barrier在dispatch_get_global_queue創建的并行隊列中不起作用,需要使用dispatch_queue_create來創建的并行隊列才可以
    //dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_queue_t concurrentQueue = dispatch_queue_create("com.concurrent.queue", DISPATCH_QUEUE_CONCURRENT);
    dispatch_async(concurrentQueue, ^(){
        [self p_printThread:1];
    });
    dispatch_async(concurrentQueue, ^(){
        [self p_printThread:2];
    });
    dispatch_async(concurrentQueue, ^(){
        [self p_printThread:3];
    });
    dispatch_barrier_async(concurrentQueue, ^(){
        [self p_printThread:0];
    });
    dispatch_async(concurrentQueue, ^(){
        [self p_printThread:4];
    });
    dispatch_async(concurrentQueue, ^(){
        [self p_printThread:5];
    });
    dispatch_async(concurrentQueue, ^(){
        [self p_printThread:6];
    });

打印結果:

<NSThread: 0x600000079300>{number = 4, name = (null)}-------2
<NSThread: 0x6000000790c0>{number = 5, name = (null)}-------3
<NSThread: 0x610000076100>{number = 3, name = (null)}-------1
<NSThread: 0x610000076100>{number = 3, name = (null)}-------0
<NSThread: 0x610000076100>{number = 3, name = (null)}-------4
<NSThread: 0x600000079300>{number = 4, name = (null)}-------6
<NSThread: 0x600000078d40>{number = 6, name = (null)}-------5

結論:運行多次后可以看出,Barrier的任務0總是在任務1、2、3之后,而且總是在任務4、5、6之前,但是任務1、2、3的執行順序不定,任務4、5、6的執行順序也不定。Barrier的任務就像“柵欄”一樣隔開了前后的任務。

3. Semaphore

Semaphore作用:信號量可以用來控制同時訪問資源的線程數量:比如系統只有兩個資源可以用,有三個線程要訪問,那么只能允許兩個線程同時訪問,第三個線程應當等待資源被釋放后再訪問。使用信號量可以實現類似于NSOperationQueue里的并發控制:信號數>0,執行任務;信號數<=0,阻塞線程
示例代碼:

// 下面的例子只允許3個線程同時執行
dispatch_semaphore_t semaphore = dispatch_semaphore_create(3);// 創建一個信號量,初始值為3
    dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    for (int i=0; i<10; i++) {
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);// 計數-1
        dispatch_async(concurrentQueue, ^{
            [self p_printThread:i];
            sleep(5);
            dispatch_semaphore_signal(semaphore);// 計數+1
        });
    }

打印結果:
<NSThread: 0x608000077b80>{number = 5, name = (null)}-------2
<NSThread: 0x610000074fc0>{number = 3, name = (null)}-------0
<NSThread: 0x6000000787c0>{number = 4, name = (null)}-------1

<NSThread: 0x6000000787c0>{number = 4, name = (null)}-------3
<NSThread: 0x610000074fc0>{number = 3, name = (null)}-------4
<NSThread: 0x608000077b80>{number = 5, name = (null)}-------5

<NSThread: 0x6000000787c0>{number = 4, name = (null)}-------7
<NSThread: 0x608000077b80>{number = 5, name = (null)}-------6
<NSThread: 0x610000074fc0>{number = 3, name = (null)}-------8

<NSThread: 0x610000074fc0>{number = 3, name = (null)}-------9
結論:由于信號量的值為3,每次只能同時執行3個線程里的任務

4. NSOperationQueue

NSOperationQueue作用:
1.將NSOperation添加到NSOperationQueue,使其異步執行 === GCD并行異步隊列。2.NSOperationQueue可以設置依賴關系 ~= GCD Group notify / GCD Group Wait / GCD Barrier。
3.可以設置最大并發數量(同時執行的線程數) === GCD 信號量
示例代碼:

NSOperationQueue *operationQueue = [NSOperationQueue new];
    NSBlockOperation *blockOperation1 = [NSBlockOperation blockOperationWithBlock:^{
        [self p_printThread:1];
        sleep(5);
    }];
    NSBlockOperation *blockOperation2 = [NSBlockOperation blockOperationWithBlock:^{
        [self p_printThread:2];
        sleep(5);
    }];
    NSBlockOperation *blockOperation3 = [NSBlockOperation blockOperationWithBlock:^{
        [self p_printThread:3];
        sleep(5);
    }];
    NSBlockOperation *blockOperation4 = [NSBlockOperation blockOperationWithBlock:^{
        [self p_printThread:4];
        sleep(5);
    }];
    
    // 2.NSOperationQueue可以設置依賴關系 ~=  GCD Group notify / GCD Group Wait / GCD Barrier
    [blockOperation1 addDependency:blockOperation2];
  
    // 3.可以設置最大并發數量(同時執行的線程數) === GCD 信號量
    operationQueue.maxConcurrentOperationCount = 1;

    [operationQueue addOperations:@[blockOperation1, blockOperation2, blockOperation3, blockOperation4] waitUntilFinished:YES];

打印結果:

<NSThread: 0x600000078300>{number = 3, name = (null)}-------2

<NSThread: 0x600000078300>{number = 3, name = (null)}-------1

<NSThread: 0x60000007aa80>{number = 4, name = (null)}-------3

<NSThread: 0x60000007aa80>{number = 4, name = (null)}-------4

結論:運行多次可以看出,每次只能執行一個線程里的任務(這個類似信號量的控制);雖然任務1、2、3、4的順序不定,但是任務1總是在任務2的后面(類似group的notify和wait)。對比可以看出NSOperationQueue使用更方便一些,語法也更接近Objective-C。

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

推薦閱讀更多精彩內容