为什么不活动的并发队列阻塞了完整的函数执行?

Why inactive concurrent queue blocking the full function execution?

第 1 步:声明一个并发队列 .initialInactive

第 2 步:调用具有同步闭包的函数。

let concurrentQueue = DispatchQueue(label: "com.semaphore", attributes: [.concurrent, .initiallyInactive])
func call() {
    print("1")
    print("7")
    concurrentQueue.sync {
    }
    print("13")
}

输出:1、7

下面执行

func call() {
    print("1")
    print("7")
    concurrentQueue.activate()
    concurrentQueue.sync {
    }
    print("13")
}

输出:1、7、13

您使用 sync 进行了调用,因此调用将等待块被安排并完成。队列处于非活动状态,因此它无法调度块。因此,块无法完成,sync 无法 return。您是否希望 sync 有不同的行为?

如果您希望所有进程在启动前等待某个条件,此结构很有用。例如,您可以创建一个非活动队列来保护对需要初始化的内容的访问(例如登录或从磁盘读取配置)。初始化后,它可以调用 .activate(),所有这些其他进程都将启动。如果系统已经初始化,.sync {} 调用将立即 return。