简体   繁体   English

CoreData:使用NSConfinementConcurrencyType并在串行分派队列中使用此上下文分派所有操作是否安全?

[英]CoreData: would it be safe using NSConfinementConcurrencyType and dispatch all operations using this context on a serial dispatch queue?

从字面上看,这种并发类型需要特定的线程,但是使用串行队列会更容易,但是在串行调度队列上使用NSConfinementConcurrencyType并发类型的上下文是否安全?

No, having a serial queue does not guarantee the operations will execute on the same thread: 不,拥有串行队列并不能保证操作将在同一线程上执行:

The Concurrency Programming Guide specifies 并发编程指南指定

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. 串行队列通常用于同步对特定资源的访问。

Why don't you just use the NSPrivateQueueConcurrencyType? 您为什么不只使用NSPrivateQueueConcurrencyType? It will make your code cleaner and thread safe. 这将使您的代码更清洁,线程更安全。 You just need to call -performBlock: or -performBlockAndWait: when accessing the context from somewhere other than the block that initialized the context. 从初始化上下文的块之外的其他位置访问上下文时,只需要调用-performBlock:-performBlockAndWait:

As long as you're sure you only use that queue with the context, yes, that's completely fine. 只要您确定只将队列与上下文一起使用,是的,那完全没问题。

Core Data doesn't care about the thread so much as it cares about concurrent access. Core Data并不关心线程,而是关心并发访问。 If you serialize access, you're safe, however you choose to do it. 如果序列化访问,则很安全,但是您选择这样做。 You could use NSRecursiveLock or semaphores or whatever works for you. 您可以使用NSRecursiveLock或信号量或任何适合您的方法。

Note that the newer concurrency models are queue based. 请注意,较新的并发模型是基于队列的。 NSPrivateQueueConcurrencyType does not guarantee that operations are always performed on the same thread, even when you use performBlock: . NSPrivateQueueConcurrencyType 不能保证始终在同一线程上执行操作,即使您使用performBlock: They happen on a private queue and might run on different threads at different times. 它们发生在专用队列上,并且可能在不同时间在不同线程上运行。 If you can manage your queue and your access well enough to do this yourself, it's reasonable to do so. 如果您可以自己管理队列和访问权限,足以自己完成此操作,则这样做是合理的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM