在Grand Central Dispatch中使用串行队列的dispatch_async与dispatch_sync [英] dispatch_async vs. dispatch_sync using Serial Queues in Grand Central Dispatch

查看:109
本文介绍了在Grand Central Dispatch中使用串行队列的dispatch_async与dispatch_sync的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我喜欢Grand Central Dispatch,并且在使用它之后相对成功,但这是我不完全理解的。

OK, I love Grand Central Dispatch and after using it with relative success but this is something I don't fully understand.

假设我创建了自己的序列号队列使用

Suppose I have created my own serial queue using

dispatch_queue_t myQueue;
myQueue = dispatch_queue_create("myQueue", NULL);

之后我这样做:

dispatch_async(myQueue, ^{
  [self doStuff1];
});

// and a few lines later...

dispatch_sync(myQueue, ^{
  [self doStuff2];
});

第一次发送是异步的。那么,它会同时完成,对吧?如果myQueue是串行的怎么办?串行队列如何并行处理,或者如果你不顺序处理?

The first dispatch is async. So, it will be done concurrently, right? How can that be if myQueue is serial? How can a serial queue do things in parallel or, if you will, out of order?

谢谢

推荐答案

dispatch_async()表示该块已入队并且 dispatch_async()返回在块执行之前将另一个任务/块(可能)排入队列。

dispatch_async() means that the block is enqueued and dispatch_async()returns to enqueueing another task/block (possibly) prior to the block being executed.

使用 dispatch_sync(), block被排队,函数将不会继续将另一个任务/块排队,直到执行该块为止。

With dispatch_sync(), the block is enqueued and the function will not continue enqueueing another task/block until the block is executed.

这些块仍然是串行执行的。你可以执行100 dispatch_async()调用,每个调用都有一个休眠100秒的块,而且速度非常快。在同一个串行队列上调用 dispatch_sync(),然后 dispatch_sync()将返回~10,000秒后。

The blocks are still executed serially. You could execute 100 dispatch_async() calls, each with a block that sleeps for 100 seconds, and it'd be really fast. Follow that with a call to dispatch_sync() on the same serial queue and dispatch_sync() will return ~10,000 seconds later.

更简单地说:

dispatch_async(serialQ, block1);
dispatch_async(serialQ, block2);
dispatch_sync(serialQ, block3);

block1 将在<$ c之前执行$ c> block2 将在 block3 之前执行。这是串行队列保证的顺序。

block1 will be executed before block2 which will be executed before block3. That is the order guaranteed by the serial queue.

但是,对 dispatch_async()的调用可能会返回 之前任何一个块开始执行。在执行所有三个块之前, dispatch_sync()返回!

However, the calls to dispatch_async() may return before any of the blocks start executing. The dispatch_sync() will not return before all three blocks are executed!

这篇关于在Grand Central Dispatch中使用串行队列的dispatch_async与dispatch_sync的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆