Grand Central Dispatch async vs sync

C.J*_*hns 29 iphone grand-central-dispatch ios

我正在阅读关于GCD调度队列的文档,并且在其中他们说队列是FIFO,所以我想知道这对异步/同步调度有什么影响?

从我的理解异步执行事情的顺序,它获取的东西,而同步执行串行..

但是当你编写你的GCD代码时,你决定了事情发生的顺序..所以只要你知道你的代码中发生了什么,你应该知道事情执行的顺序.

我的问题是,这里有异步的好处吗?我对这两件事的理解中遗漏了什么.

jkh*_*jkh 32

不幸的是,第一个答案并不完全.是的,同步将阻止,异步不会,但是需要考虑其他语义.调用dispatch_sync()还会导致代码等到该队列上的每个待处理项都完成执行,同时使其成为所述工作的同步点.dispatch_async()将简单地将工作提交到队列并立即返回,之后它将"在某个时刻"执行,您需要以其他方式跟踪该工作的完成(通常通过在另一个dispatch_async中嵌套一个dispatch_async - 请参阅例如手册页).


Ton*_*ion 19

sync表示函数将BLBL当前线程直到它完成,async意味着它将在后台处理,函数将不会阻塞当前线程.

如果要串行执行块,请检查是否创建了串行调度队列


小智 8

从手册页:

基本面

Conceptually, dispatch_sync() is a convenient wrapper around
dispatch_async() with the addition of a semaphore to wait for completion
of the block, and a wrapper around the block to signal its completion.
See dispatch_semaphore_create(3) for more information about dispatch sem-
aphores. The actual implementation of the dispatch_sync() function may be
optimized and differ from the above description.
Run Code Online (Sandbox Code Playgroud)


Vin*_*dan 5

任务可以同步或异步执行。

同步功能仅在任务完成后才返回当前队列上的控件。它阻止队列并等待直到任务完成。

发送任务以在不同队列上执行之后,异步函数立即返回当前队列上的控制。它不会等到任务完成。它不会阻塞队列。

仅在异步中,我们可以添加延迟 ->asyncAfter(deadline: 10..