除了系統提供的全域佇列與主佇列,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
dispatch_queue_create 的第二個參數在新版可直接傳 DISPATCH_QUEUE_SERIAL,比寫 0 更清楚。若想建立並行佇列,則傳 DISPATCH_QUEUE_CONCURRENT。另外,dispatch_release 是 MRC 時代的寫法;在 ARC 環境下 GCD 物件由編譯器管理,不需要也不應該手動釋放。順序保證不代表執行緒唯一:系統可能在空閒時切換執行緒,但「同一時間只有一個任務在跑」的序列語意不會被破壞。