-->

sqlite3 multithreading in objective c

2019-02-18 13:00发布

问题:

I am running a background thread in my application with dispatch_async and some times my main thread and background thread both access the database same time and this was giving me a database error and I tried to solve it by using sqlite3_threadsafe() which was always returning 2 i.e, i cannot use the same database connection in two threads and I want it to return 1 can anyone help me in this regard

回答1:

I think you're pursuing the wrong approach. SQLite isn't reliably threadsafe no matter how you compile it — see the 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.

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.



回答2:

You can add all of your access statements to, therefore you are always on the main thread when access the sqlite store.

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