search

Home  >  Q&A  >  body text

ios - CoreData多线程的同步问题

CoreData问题:需要对persistentCoordina加锁,但不知道加在哪些代码合适。不同的NSManagedObjectContext,但公用同一个NSPersistentCoordinator,是否允许两个线程同时进行读操作,而不对NSPersistentCoordinator进行lock?还是不管读和写,都需要对lock coordinator?
之前虽然是多线程操作coredata,没加lock,但是由于工作线程并没有很频繁的操作数据库,因此没出问题。但是现在我的工作线程需要2分钟一次对数据库进行查询、更新的逻辑,所以程序有时可以运行,有时executeFetch时候会卡死,报的错误是deadlock,死锁!很奇怪,我这时候根本就没对数据库加过锁啊!
是因为,coordinator对所有的操作,都会序列化(serialize operations),然后多线程操作coredata时候,我代码里面没有lock coordinator,所以就出现了deadlock的错误?
多谢大家的关注或回答啊!

PHPzPHPz2872 days ago648

reply all(2)I'll reply

  • 大家讲道理

    大家讲道理2017-04-17 11:08:30

    Once every two minutes, how long does it take? Does each operation take seconds?
    If it takes seconds, add a lock to the thread yourself. If it takes longer, consider caching the data into memory, etc.

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 11:08:30

    First of all, it is recommended not to operate the same NSPersistentStoreCoordinator in multiple threads.
    Multi-threaded read and write operations on the same NSPersistentStoreCoordinator may indeed cause deadlock. Therefore, it is recommended to lock NSPersistentStoreCoordinator for every write operation to avoid thinking

    reply
    0
  • Cancelreply