您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 技巧大全

iOS 多線程 GCD 基本用法:六種「同步/異步 × 隊列類型」組合實測

編輯:iOS 技巧大全

GCD 只有兩個核心概念:任務(要做什麼)與隊列(任務放在哪裡)。把「同步或異步」與「並發或串行」交叉組合,就會得到六種行為模式,以下逐一實測。

1. 異步 + 並發隊列:同時開啟多條線程

- (void)asyncConcurrent {
    // 方式一:自行建立並發隊列
    dispatch_queue_t queue = dispatch_queue_create("com.kyle.queue", DISPATCH_QUEUE_CONCURRENT);

    // 方式二:取得全域並發隊列
    // dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

    dispatch_async(queue, ^{
        for (NSInteger i = 0; i < 3; i++) NSLog(@"this is first %@", [NSThread currentThread]);
    });
    dispatch_async(queue, ^{
        for (NSInteger i = 0; i < 3; i++) NSLog(@"this is second %@", [NSThread currentThread]);
    });
    dispatch_async(queue, ^{
        for (NSInteger i = 0; i < 3; i++) NSLog(@"this is third %@", [NSThread currentThread]);
    });
}

2. 同步 + 並發隊列:不會開新線程

- (void)syncConcurrent {
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

    dispatch_sync(queue, ^{ NSLog(@"this is first %@", [NSThread currentThread]); });
    dispatch_sync(queue, ^{ NSLog(@"this is second %@", [NSThread currentThread]); });
    dispatch_sync(queue, ^{ NSLog(@"this is third %@", [NSThread currentThread]); });
}

三個任務依序在同一條線程上執行完畢才繼續往下。

3. 異步 + 串行隊列:會開新線程,但任務串行

- (void)asyncSerial {
    dispatch_queue_t queue = dispatch_queue_create("com.kyle.queue", DISPATCH_QUEUE_SERIAL);
    // 也可寫成 dispatch_queue_create("com.kyle.queue", NULL);

    dispatch_async(queue, ^{ NSLog(@"this is first %@", [NSThread currentThread]); });
    dispatch_async(queue, ^{ NSLog(@"this is second %@", [NSThread currentThread]); });
    dispatch_async(queue, ^{ NSLog(@"this is third %@", [NSThread currentThread]); });
}

4. 同步 + 串行隊列:當前線程依序執行

- (void)syncSerial {
    dispatch_queue_t queue = dispatch_queue_create("com.kyle.queue", DISPATCH_QUEUE_SERIAL);

    dispatch_sync(queue, ^{ NSLog(@"this is first %@", [NSThread currentThread]); });
    dispatch_sync(queue, ^{ NSLog(@"this is second %@", [NSThread currentThread]); });
    dispatch_sync(queue, ^{ NSLog(@"this is third %@", [NSThread currentThread]); });
}

5. 異步 + 主隊列:任務都在主線程

- (void)asyncMain {
    dispatch_queue_t queue = dispatch_get_main_queue();

    dispatch_async(queue, ^{
        NSLog(@"this is first %@",  [NSThread currentThread]);
        NSLog(@"this is second %@", [NSThread currentThread]);
        NSLog(@"this is third %@",  [NSThread currentThread]);
    });
}

6. 同步 + 主隊列:直接造成死鎖

- (void)syncMain {
    NSLog(@"begin");

    dispatch_queue_t queue = dispatch_get_main_queue();
    dispatch_sync(queue, ^{ NSLog(@"this is %@", [NSThread currentThread]); });

    NSLog(@"end");   // 這行永遠不會執行
}

原因很單純:主隊列中的任務必須等當前方法返回後才有機會執行,而 dispatch_sync 又會阻塞當前(主)線程等待任務完成,於是雙方互相等待,形成死鎖。這是 GCD 面試的必考陷阱,務必記牢:不要在主隊列上使用同步分派。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved