swift - 为什么带同步的并发队列表现得像串行队列?

标签 swift concurrency grand-central-dispatch concurrent-queue

谁能帮助我理解我创建的这段代码:

let cq = DispatchQueue(label: "downloadQueue", attributes: .concurrent)
cq.sync {
for i in 0..<10 {
    sleep(2)
    print(i)
  }
}

print("all finished!")

输出顺序为 1->10,中间等待 2 秒。最后会打印出all finished

我理解最后一部分。 但是我的问题是:

并发队列不应该同时启动多个任务吗? 所以我最初的想法是:1-10 的打印应该并发,不一定按顺序进行。

谁能解释一下在并发队列上调用sync 的目的,并举例说明为什么以及何时需要它?

最佳答案

如果你想演示它们并发运行,你应该单独分派(dispatch)这 10 个任务:

let cq = DispatchQueue(label: "downloadQueue", attributes: .concurrent)

for i in 0..<10 {
    cq.async {
        sleep(2)
        print(i)
    }
}
print("all finished queuing them!")

注意:

  • 并发队列有 10 个分派(dispatch),没有一个。

    每个分派(dispatch)的任务相对于分派(dispatch)到该队列的其他任务并发运行(这就是为什么我们需要多次分派(dispatch)来说明并发性)。

  • 另请注意,我们是异步调度的,因为我们不想在调度下一个任务之前调用队列来等待每个已调度的任务。


你问:

So my original thought was: the 1-10 printing should be done concurrently, not necessarily in the serial order.

因为它们在一个调度中,它们将作为一个任务运行,按顺序运行。您需要将它们放在单独的调度中才能看到它们同时运行。

你继续问:

Could anyone explain the purpose of sync call on concurrent queue and give me an example why and when we need it?

sync 与目标队列是串行还是并发无关。 sync 仅指示调用 线程的行为,即调用者是否应该等待分派(dispatch)的任务完成。在这种情况下,你真的不想等待,所以你应该使用 async

作为一般规则,您应该避免调用 sync 除非 (a) 您绝对必须这样做; (b) 您愿意阻塞调用线程,直到 sync 任务运行。因此,除了极少数异常(exception),应该使用 async。而且,也许不用说,我们绝不会阻塞主线程超过几毫秒。

虽然通常会避免在并发调度队列上使用sync,但您可能会遇到的一个例子是“读写器”同步模式。在这种情况下,“读取”是同步发生的(因为您需要等待结果),但是“写入”是异步发生的并带有屏障(因为您不需要等待,但您不希望它与任何事情同时发生其他在那个队列上)。使用 GCD 进行同步的详细讨论(尤其是读写器模式)可能超出了这个问题的范围。但是在网络或 StackOverflow 上搜索“GCD 读写器”,您会发现关于该主题的讨论。)


让我们使用 OSLog 以图形方式说明我修改后的代码再现在 Instruments 的“兴趣点”工具中创建间隔:

import os.log

private let log = OSLog(subsystem: "Foo", category: .pointsOfInterest)

class Foo {
    func demonstration() {
        let queue = DispatchQueue(label: "downloadQueue", attributes: .concurrent)

        for i in 0..<10 {
            queue.async { [self] in
                let id = OSSignpostID(log: log)
                os_signpost(.begin, log: log, name: "async", signpostID: id, "%d", i)
                spin(for: 2)
                os_signpost(.end, log: log, name: "async", signpostID: id)
            }
        }
        print("all finished queuing them!")
    }

    func spin(for seconds: TimeInterval) {
        let start = CACurrentMediaTime()
        while CACurrentMediaTime() - start < seconds { }
    }
}

当我在 Instruments(例如“Product”»“Profile”)中对此进行分析时,选择“Time Profiler”模板(其中包括“Points of Interest”工具),我看到了正在发生的事情的图形时间线:

enter image description here

因此,让我提请您注意上述两个有趣的方面:​​

  1. 并发队列并发运行任务,但是因为我iPhone的CPU只有六个核心,所以实际上只有六个可以同时运行。接下来的四个必须等到核心可用于该特定工作线程。

    请注意,此演示之所以有效,是因为我不仅调用了 sleep,而且我正在旋转所需的时间间隔,以更准确地模拟一些缓慢的阻塞任务。与 sleep 相比,Spinning 更适合慢速同步任务。

  2. 正如您所指出的,这说明并发任务可能不会按照它们提交的精确顺序出现。这是因为(a)他们都接连排队的速度太快了; (b) 它们并发运行:关于哪个并发运行的线程首先获取日志语句(或“兴趣点”间隔)存在“竞争”。

    归根结底,对于那些并发运行的任务,由于竞争,它们可能不会按顺序运行。这就是并发执行的工作原理。

关于swift - 为什么带同步的并发队列表现得像串行队列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71233769/

相关文章:

ios - 更改导航栏后退按钮的厚度

ios - 使用Combine Publishers的401重试机制

swift - 我该如何解决这个错误? : Type '(String!, args: CVaListPointer)' does not conform to protocol 'StringLiteralConvertible'

java - 进一步并行化两个Java的parallelStream()计算

scala - Monoid 的错误累积

Java用非 volatile 重新排序 volatile 写入

ios - 如果 CoreMotion 的更新处理程序完成速度不够快怎么办?

swift - ReplayKit 不会在一个 session 中录制两次

c - 调度源阅读器 - 如何检测文件结尾?

ios - 在 DispatchAfter 中将 DispatchTime 作为参数传递