GCD10: 用GCD构建自己的分派队列

想要创建你自己的、独特命名的分派队列:
使用 dispatch_queue_create 函数。 

讨论:

利用 GCD,你可以创建你自己的串行分派队列:
我们将使用 dispatch_queue_create 函数创建串行队列。这个函数的第一个参数是 C 字符串(char *),它将唯一标识系统中的串行队列。我强调系统的原因是这个标识符是一个全系统标识符,意味着你的 APP 创建了一个新的带有 serialQueue1 标识符的串行队列,和别人的 APP 的标识符相同,GCD 无法确定创建一个新的有相同命名的串行队列的结果。因为这 一点,Apple 强烈推荐你使用反向 DNS 格式的标识符,反向 DNS 标识符通常按照这样的方法构建:com.COMPANY.PRODUCT.IDENTIFIER。例如,我可以创建 2 个串行队列并分别命名为: 
com.pixolity.GCD.serialQueue1 
com.pixolity.GCD.serialQueue2
创建了串行队列之后,你可以开始使用各种 GCD 功能向它分配任务。一旦自己创建的串行队列使用完成工作后,你必须使用 dispatch_release 释放它。
例子:
dispatch_queue_t firstSerialQueue = dispatch_queue_create("com.pixolity.GCD.serialQueue1", 0);
dispatch_async(firstSerialQueue, ^{
NSUInteger counter = 0;
for (counter = 0;
counter < 5;
counter++){
NSLog(@"First iteration, counter = %lu", (unsigned long)counter);
}
});

我们可以修正同样的模板代买来使用dispatch_async_f 函数而不是dispatch_async 函数,就像这样:

void firstIteration(void *paramContext){
NSUInteger counter = 0;
for (counter = 0;
counter < 5;
counter++){
NSLog(@"First iteration, counter = %lu", (unsigned long)counter);
}
}
void secondIteration(void *paramContext){
NSUInteger counter = 0;
for (counter = 0;
counter < 5;
counter++){
NSLog(@"Second iteration, counter = %lu", (unsigned long)counter);
}
}
void thirdIteration(void *paramContext){
NSUInteger counter = 0;
for (counter = 0;
counter < 5;
counter++){
NSLog(@"Third iteration, counter = %lu", (unsigned long)counter);
}
}

- (BOOL) application:(UIApplication *)applicationdidFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
dispatch_queue_t firstSerialQueue =
dispatch_queue_create("com.pixolity.GCD.serialQueue1", 0);
dispatch_async_f(firstSerialQueue, NULL, firstIteration);
dispatch_async_f(firstSerialQueue, NULL, secondIteration);
dispatch_async_f(firstSerialQueue, NULL, thirdIteration);
dispatch_release(firstSerialQueue);
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
原文地址:https://www.cnblogs.com/safiri/p/4079480.html