dispatch_queue_t queue = dispatch_queue_create("Database_Queue", DISPATCH_QUEUE_CONCURRENT);dispatch_async(queue, ^{NSLog(@"reading data1");});dispatch_async(queue, ^{NSLog(@"reading data2");});dispatch_barrier_async(queue, ^{NSLog(@"writing data1");[NSThread sleepForTimeInterval:1];});dispatch_async(queue, ^{[NSThread sleepForTimeInterval:1];NSLog(@"reading data3");});
执行结果如下:
GCDTests[13360:584316] reading data2GCDTests[13360:584317] reading data1GCDTests[13360:584317] writing data1GCDTests[13360:584317] reading data3
我们将写数据的操作放在dispatch_barrier_async中,这样能确保在写数据的时候会等待前面的读操作完成,而后续的读操作也会等到写操作完成后才能继续执行,提高文件读写的执行效率。
dispatch_queue_t queue = dispatch_queue_create("myqueue", DISPATCH_QUEUE_CONCURRENT);//并发的运行一个block任务5次dispatch_apply(5, queue, ^(size_t i) {NSLog(@"do a job %zu times",i+1);});NSLog(@"go on");
输出结果:
GCDTests[10029:760640] do a job 2 timesGCDTests[10029:760640] do a job 1 timesGCDTests[10029:760640] do a job 3 timesGCDTests[10029:760640] do a job 5 timesGCDTests[10029:760640] do a job 4 timesGCDTests[10029:760640] go on
void dispatch_block_notify(dispatch_block_t block, dispatch_queue_t queue,dispatch_block_t notification_block);
具体使用的方法:
dispatch_queue_t queue = dispatch_queue_create("queue", DISPATCH_QUEUE_SERIAL);dispatch_block_t previousBlock = dispatch_block_create(0, ^{NSLog(@"previousBlock begin");[NSThread sleepForTimeInterval:1];NSLog(@"previousBlock done");});dispatch_async(queue, previousBlock);dispatch_block_t notifyBlock = dispatch_block_create(0, ^{NSLog(@"notifyBlock");});//当previousBlock执行完毕后,提交notifyBlock到global queue中执行dispatch_block_notify(previousBlock, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), notifyBlock);
运行结果:
GCDTests[17129:895673] previousBlock beginGCDTests[17129:895673] previousBlock doneGCDTests[17129:895673] notifyBlock
dispatch_queue_t queue = dispatch_queue_create("queue", DISPATCH_QUEUE_CONCURRENT);dispatch_group_t group = dispatch_group_create();//将任务异步地添加到group中去执行dispatch_group_async(group,queue,^{ NSLog(@"block1"); });dispatch_group_async(group,queue,^{ NSLog(@"block2"); });dispatch_group_wait(group,DISPATCH_TIME_FOREVER);NSLog(@"go on");
执行结果如下,只有block1跟block2执行完毕后才会执行dispatch_group_wait后面的内容。
GCDTests[954:41031] block2GCDTests[954:41032] block1GCDTests[954:40847] go on
void dispatch_group_notify(dispatch_group_t group, //要观察的groupdispatch_queue_t queue, //block执行的队列dispatch_block_t block); //当group中所有任务执行完毕之后要执行的block
简单的示意用法:
dispatch_queue_t queue = dispatch_queue_create("queue", DISPATCH_QUEUE_CONCURRENT);dispatch_group_t group = dispatch_group_create();dispatch_group_async(group,queue,^{ NSLog(@"block1"); });dispatch_group_async(group,queue,^{ NSLog(@"block2"); });dispatch_group_notify(group, dispatch_get_main_queue(), ^{NSLog(@"done");});NSLog(@"go on");
可以看到如下的执行结果
GCDTests[1046:45104] go onGCDTests[1046:45153] block1GCDTests[1046:45152] block2GCDTests[1046:45104] done