3

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
  • You can't access a SQLIte DB simultaneously from two different threads. Commented May 8, 2012 at 3:14

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

The FMDB solution does precisely that, creates a queue just for database interaction.
Inundating SQLite with commands can result in SQLITE_BUSY errors. Best to pace those commands and avoid aggressive multithreading if possible.
1

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
});

1 Comment

Probably better to use a dedicated custom serial queue, as Tommy suggested, for this rather than risking blocking/deadlocking the main queue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.