Grand Central Dispatch async vs sync [duplicate]

强颜欢笑 提交于 2019-12-17 22:09:58

问题


I'm reading the docs on dispatch queues for GCD, and in it they say that the queues are FIFO, so I am woundering what effect this has on async / sync dispatches?

from my understand async executes things in the order that it gets things while sync executes things serial..

but when you write your GCD code you decide the order in which things happen.. so as long as your know whats going on in your code you should know the order in which things execute..

my questions are, wheres the benefit of async here? am I missing something in my understanding of these two things.


回答1:


sync means the function WILL BLOCK the current thread until it has completed, async means it will be handled in the background and the function WILL NOT BLOCK the current thread.

If you want serial execution of blocks check out the creation of a serial dispatch queue




回答2:


The first answer isn't quite complete, unfortunately. Yes, sync will block and async will not, however there are additional semantics to take into account. Calling dispatch_sync() will also cause your code to wait until each and every pending item on that queue has finished executing, also making it a synchronization point for said work. dispatch_async() will simply submit the work to the queue and return immediately, after which it will be executed "at some point" and you need to track completion of that work in some other way (usually by nesting one dispatch_async inside another dispatch_async - see the man page for example).




回答3:


From the man page:

FUNDAMENTALS

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.



回答4:


Tasks can be performed synchronously or asynchronously.

Synchronous function returns the control on the current queue only after task is finished. It blocks the queue and waits until the task is finished.

Asynchronous function returns control on the current queue right after task has been sent to be performed on the different queue. It doesn't wait until the task is finished. It doesn't block the queue.

Only in Asynchronous we can add delay -> asyncAfter(deadline: 10..



来源:https://stackoverflow.com/questions/9200558/grand-central-dispatch-async-vs-sync

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!