简体   繁体   English

目标c中的sqlite3多线程

[英]sqlite3 multithreading in objective c

我在我的应用程序中使用dispatch_async运行后台线程,有时我的主线程和后台线程都同时访问数据库,这给了我一个数据库错误,我试图通过使用sqlite3_threadsafe()来解决它,它始终返回2即,我不能在两个线程中使用相同的数据库连接,我希望它返回1可以任何人在这方面帮助我

I think you're pursuing the wrong approach. 我认为你正在采取错误的做法。 SQLite isn't reliably threadsafe no matter how you compile it — see the FAQ . 无论你如何编译它,SQLite都不是可靠的线程安全的 - 请参阅FAQ Even if SQLite is compiled for thread safety, the same database may not be used from multiple threads if any transactions are pending or any statements remain unfinalised. 即使为了线程安全而编译SQLite,如果任何事务处于挂起状态或任何语句仍未完成,则不能从多个线程使用相同的数据库。

The recommendations above to use Grand Central Dispatch to funnel all SQLite accesses into a serial dispatch queue are the right way to proceed in my opinion, though I'd be more likely to recommend that you create your own queue rather than use the main queue for the simple reason that you can reliably dispatch_sync when you want to wait on a result. 上面建议使用Grand Central Dispatch将所有SQLite访问汇集到一个串行调度队列中是我认为正确的方法,尽管我更有可能建议您创建自己的队列而不是使用主队列您希望等待结果时可以可靠地调度_sync的简单原因。

You can add all of your access statements to, therefore you are always on the main thread when access the sqlite store. 您可以添加所有访问语句,因此在访问sqlite存储时,您始终位于主线程上。

dispatch_async(dispatch_get_main_queue(), ^ {
    //code goes here
});

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

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