GCD 中的并发队列与串行队列 [英] Concurrent vs serial queues in GCD

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

问题描述

我正在努力完全理解 GCD 中的并发和串行队列.我有一些问题,希望有人能清楚地回答我.

I'm struggling to fully understand the concurrent and serial queues in GCD. I have some issues and hoping someone can answer me clearly and at the point.

  1. 我读到串行队列的创建和使用是为了一个接一个地执行任务.但是,如果出现以下情况会发生什么:

  1. I'm reading that serial queues are created and used in order to execute tasks one after the other. However, what happens if:

  • 我创建了一个串行队列
  • 我使用 dispatch_async(在我刚刚创建的串行队列上)三次来分派三个块 A、B、C
  • I create a serial queue
  • I use dispatch_async (on the serial queue I just created) three times to dispatch three blocks A,B,C

是否会执行三个block:

Will the three blocks be executed:

  • 按顺序 A,B,C 因为队列是串行的

  • in order A,B,C because the queue is serial

我读到我可以在并发队列上使用 dispatch_sync 以便一个接一个地执行块.在那种情况下,为什么还存在串行队列,因为我总是可以使用并发队列,在那里我可以根据需要同步调度尽可能多的块?

I'm reading that I can use dispatch_sync on concurrent queues in order to execute blocks one after the other. In that case, WHY do serial queues even exist, since I can always use a concurrent queue where I can dispatch SYNCHRONOUSLY as many blocks as I want?

谢谢你的好解释!

推荐答案

一个简单的例子:你有一个需要一分钟来执行的块.您将其从主线程添加到队列中.我们来看看这四种情况.

A simple example: you have a block that takes a minute to execute. You add it to a queue from the main thread. Let's look at the four cases.

  • async - 并发:代码在后台线程上运行.控制立即返回到主线程(和 UI).该块不能假设它是该队列上运行的唯一块
  • async - 串行:代码在后台线程上运行.控制立即返回到主线程.该块可以假定它是该队列中唯一运行的块
  • sync - 并发:代码在后台线程上运行,但主线程等待它完成,阻止对 UI 的任何更新.该块不能假设它是该队列上运行的唯一块(我可以在几秒钟前使用 async 添加另一个块)
  • sync - 串行:代码在后台线程上运行,但主线程等待它完成,阻止对 UI 的任何更新.该块可以假定它是该队列中唯一运行的块
  • async - concurrent: the code runs on a background thread. Control returns immediately to the main thread (and UI). The block can't assume that it's the only block running on that queue
  • async - serial: the code runs on a background thread. Control returns immediately to the main thread. The block can assume that it's the only block running on that queue
  • sync - concurrent: the code runs on a background thread but the main thread waits for it to finish, blocking any updates to the UI. The block can't assume that it's the only block running on that queue (I could have added another block using async a few seconds previously)
  • sync - serial: the code runs on a background thread but the main thread waits for it to finish, blocking any updates to the UI. The block can assume that it's the only block running on that queue

显然,对于长时间运行的进程,您不会使用后两个中的任何一个.当您尝试从可能在另一个线程上运行的某些内容更新 UI(始终在主线程上)时,您通常会看到它.

Obviously you wouldn't use either of the last two for long running processes. You normally see it when you're trying to update the UI (always on the main thread) from something that may be running on another thread.

这篇关于GCD 中的并发队列与串行队列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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