swift

时间:2018-10-02 08:51:28

标签: swift multithreading asynchronous grand-central-dispatch dispatch-queue

据我了解,迅速有3种DispatchQueue:

  • 主(串行)(主线程)
  • 全局(并行)(背景线程并行工作)
  • 自定义(并行或串行)

每个人都可以工作(异步或同步)

第一个问题:

主队列仅在 UI线程上工作,而不在其他线程上工作吗? 如果答案是肯定的,DispatchQueue.Main.async如何不阻止UI线程。 如果答案为否,只要DispatchQueue.global在另一个线程中工作,使用DispatchQueue.Main.async有什么好处。

第二个问题:

DispatchQueue.global(异步) DispatchQueue.global(同步)之间的区别是什么,只要此队列工作并发,并且在哪里使用每个?

第三个问题:

之间的区别是什么
  1. (串行和同步)
  2. (并发和异步)

2 个答案:

答案 0 :(得分:3)

据我了解:

队列不是线程

主队列和全局队列可能在同一线程中工作

已分派:表示将任务放入队列

如果全局队列作为 sync 主队列中调度,则调度的任务将在 Main队列的同一线程上工作和已调度的任务已添加到全局队列中, 此任务将冻结线程

如果全局队列主队列中以 async 的身份分派,则分派的任务将在主队列的其他线程上工作和已调度的任务已添加到全局队列中, 此任务不会冻结线程

如果主队列主队列中以 async 的身份分派,则分派的任务将在主队列的同一线程上工作

如果在主队列中作为同步调度的主队列将成为异常,因为进行死锁

Dispatch.sync :将任务放入队列中,直到完成为止

Dispatch.async :将任务放入队列中,而不要等到完成(任务可能在同一线程或另一个线程中工作)

  • 如果任务在全局队列上分派,并且这与主线程一致 然后任务将添加到Global queue,新线程将是 创建,任务将立即在新线程中开始工作

  • 如果任务在Main队列上分派并且与Main线程一致 那么该任务将被添加到Main queue中,并且将无法正常工作 立即直到队列中较旧的任务完成工作(因为Main 队列是顺序的)

答案 1 :(得分:2)

DispatchQueue's do not correspond to a single thread directly. The only restriction is that you are only allowed to access the UI from the main thread, which can be done through DispatchQueue.main. However, there's no guarantee that the system will dispatch your execution block to a specific thread if you call it on a specific queue.

DispatchQueue.async is a non-blocking operation, so you can execute several code blocks asynchronously on the same queue without blocking a specific thread, this is why you should always dispatch operations to the main queue asynchronously, to avoid blocking UI updates, since the main queue is solely responsible for UI related tasks. Calling async on any queue, does not guarantee that the execute will happen on a specific thread (be it background or main), it only guarantees that the operation will be executed in a non-blocking manner.

DispatchQueue.sync is a blocking operation, meaning that while a single sync code block is being executed, no other piece of code can be executed on the specific DispatchQueue, so if you dispatch a code block to the main queue synchronously, you will block UI updates and hence your app will freeze.