当串行队列上的 运行 异步任务时,有没有一种方法我们可能会面临竞争条件

Is there a way we might face race condition when running async tasks on serial queue

假设如果串行队列中的多个异步任务运行正在访问同一个共享资源,我们是否有可能面临竞争条件?

根据我添加的评论,这是摘自 Apple doc。粗体字是我强调你要找的东西。

Serial queues (also known as private dispatch queues) execute one task at a time in the order in which they are added to the queue. The currently executing task runs on a distinct thread (which can vary from task to task) that is managed by the dispatch queue. Serial queues are often used to synchronize access to a specific resource.

如果您使用的是并发队列,则可能会出现竞争条件。例如,您可以使用调度障碍来阻止它。有关详细信息,请参阅 Grand Central Dispatch In-Depth: Part 1/2

对于NSOperationNSOperationQueue同样适用。 NSOperationQueue 可以通过 maxConcurrentOperationCount 设置为 1 进行串行化。另外,通过操作使用依赖,可以同步对共享资源的访问。

不,你不能 运行 进入竞争状态,看看我在那里做了什么,当 运行 在串行队列上执行异步任务时,由于队列类型必须处理执行任务的方式,而同步和异步必须在完成一项昂贵的任务时处理应用程序的响应能力。

在并发队列上很容易运行进入竞争条件的原因是在并发队列上允许同时执行任务,因此有时不同的线程可能"racing" 执行一个动作,实际上,由于线程执行相同的动作,它们正在覆盖以前的线程工作。在串行队列中,任务是一次执行一个,因此两个线程无法竞相完成一项任务,因为它是按顺序发生的。希望对您有所帮助!