简体   繁体   中英

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? 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.

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. If you serialize access, you're safe, however you choose to do it. You could use NSRecursiveLock or semaphores or whatever works for you.

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: . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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