您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 開發(66):建立自己的 GCD 分派佇列

編輯:iOS 開發綜合

前言

除了系統提供的全域佇列與主佇列,GCD 也允許你建立自己命名的佇列——dispatch_queue_create。自訂佇列的價值在於「序列化」:同一個佇列裡的任務必定依序執行,適合保護不需要跨執行緒共用但需要順序保證的資源。

程式碼實作

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // 建立自己命名的序列佇列(第二個參數 0 代表序列)
    dispatch_queue_t firstSerialQueue =
        dispatch_queue_create("ZYAppDelegate.GCD.serialQueue1", 0);

    // 依序異步提交三個 Block
    dispatch_async(firstSerialQueue, ^{
        NSUInteger counter = 0;
        for (counter = 0; counter < 5; counter++){
            NSLog(@"First iteration, counter = %lu", (unsigned long)counter);
        }
    });

    dispatch_async(firstSerialQueue, ^{
        NSUInteger counter = 0;
        for (counter = 0; counter < 5; counter++){
            NSLog(@"Second iteration, counter = %lu", (unsigned long)counter);
        }
    });

    dispatch_async(firstSerialQueue, ^{
        NSUInteger counter = 0;
        for (counter = 0; counter < 5; counter++){
            NSLog(@"Third iteration, counter = %lu", (unsigned long)counter);
        }
    });

    // 釋放佇列
    dispatch_release(firstSerialQueue);

    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    self.viewController = [[[ZYViewController alloc] initWithNibName:@"ZYViewController" bundle:nil] autorelease];
    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];
    return YES;
}

運行結果

三組迴圈嚴格分三段輸出,且都在同一個執行緒(1303)上:

2013-05-12 11:41:59.221 [1030:1303] First iteration, counter = 0
2013-05-12 11:41:59.223 [1030:1303] First iteration, counter = 1
...
2013-05-12 11:41:59.226 [1030:1303] Second iteration, counter = 0
...
2013-05-12 11:41:59.232 [1030:1303] Third iteration, counter = 0
...
2013-05-12 11:41:59.234 [1030:1303] Third iteration, counter = 4

兩個關鍵點

  • 命名佇列的好處:字串標籤會出現在 Instruments、Crash log 與除錯器中,排查問題時能立刻知道是哪一條佇列出事。建議用「公司/App.用途.序號」的逆向式命名。
  • DISPATCH_QUEUE_SERIAL 語意:dispatch_queue_create 的第二個參數在新版可直接傳 DISPATCH_QUEUE_SERIAL,比寫 0 更清楚。若想建立並行佇列,則傳 DISPATCH_QUEUE_CONCURRENT。

另外,dispatch_release 是 MRC 時代的寫法;在 ARC 環境下 GCD 物件由編譯器管理,不需要也不應該手動釋放。順序保證不代表執行緒唯一:系統可能在空閒時切換執行緒,但「同一時間只有一個任務在跑」的序列語意不會被破壞。

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