串行调度队列如何保证资源保护? [英] How does a serial dispatch queue guarantee resource protection?
问题描述
//my_serial_queue is a serial_dispatch_queue
dispatch_async(my_serial_queue, ^{
//access a shared resource such as a bank account balance
[self changeBankAccountBalance];
});
如果我提交了100个任务,每个任务都可以访问并更改银行帐户余额,那么我知道串行队列将按顺序执行每个任务,但是在使用dispatch_async时,这些任务是否也按顺序完成?
If I submit 100 tasks that each access and mutate a bank account balance, I understand that a serial queue will execute each task sequentially, but do these tasks finish sequentially as well when using dispatch_async?
如果我异步提交给串行队列的任务#23需要很长时间才能完成怎么办?任务#24仅在任务#23完成后才开始,还是任务#24在任务#23完成之前就开始?如果是这样,任务#24在开始工作时难道不会有错误的银行帐户余额,从而破坏了数据完整性吗?
What if task #23 that I submit asynchronously to the serial queue takes a really long time to finish? Would task #24 start only when task #23 is done, or would task #24 begin before task #23 is done? If so, couldn't task #24 have the wrong bank account balance when it starts its job, thereby screwing up data integrity?
谢谢!
推荐答案
man dispatch_queue_create
说:保证了由分派到串行队列的块执行的所有内存写操作对于分派到同一队列的后续块都是可见的。因此,串行队列是序列化对可变状态的访问以避免冲突条件的一种好方法。
man dispatch_queue_create
says: "All memory writes performed by a block dispatched to a serial queue are guaranteed to be visible to subsequent blocks dispatched to the same queue." Thus, serial queues are a good way to serializing access to mutable state to avoid race conditions.
在使用时,这些任务也按顺序完成dispatch_async?
do these tasks finish sequentially as well when using dispatch_async?
是。队列决定执行策略,而不是如何对块进行排队。
Yes. The queue dictates the execution policy, not how you queue the block.
换句话说,如果队列是串行的,则使用async或sync排队不会改变它。唯一的区别是:在继续执行其余程序之前,我是否要等待此块完成? dispatch_async
=否, dispatch_sync
=是。
In other words, if the queue is serial, queueing with async or sync doesn't change that. The only difference is: do I wait for this block to complete before continuing execution of the rest of the program? dispatch_async
=no, dispatch_sync
=yes.
如果我异步提交给串行队列
的任务#23需要很长时间才能完成?
What if task #23 that I submit asynchronously to the serial queue takes a really long time to finish?
没有任何变化。串行队列始终始终等待先前出队的块(#23)完成,然后再出队并执行下一个块(#24)。如果需要考虑使队列停顿,则应在阻止代码内实现超时。
Nothing changes. A serial queue always waits for the previously dequeued block (#23) to complete before dequeuing and executing the next block (#24). If stalling the queue is a concern, you should implement a timeout inside your block code.
这篇关于串行调度队列如何保证资源保护?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!