Reputation: 3301
My Sqlite Database is accessed from various threads in my code due to which I am getting lot of Database LOCK issue.
To overcome the lock issue I am querying the DB in main thread only. The drawback of this is my main thread is busy if there are lot of queries to be executed.
I want to write a mechanism wherein all the DB calls are executed from one place (in a secondary thread) so that it can be synchronized and the caller can call from any thread.
It may be like if any module wants to execute a query it will check from the main DB Sync class whether the DB is busy or free to perform the task.
Note:- In my current implementation I am opening and closing the DB every time I want to execute the query. Will it have any performance impact ?
Any Hint in right Direction would be highly appreciated.
Upvotes: 1
Views: 1783
Reputation: 385580
Reopening the database will of course take more time than keeping it open. However, it might not be a noticeable amount of time.
I suggest you create a Grand Central Dispatch queue and use it for all database access. Here's how you create it:
// The queue needs to be a global variable, or globally accessible in some way.
dispatch_queue_t dbQueue;
// Make your sqlite3 connection global too.
sqlite3 *dbConnection;
// In your application delegate:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// usual initialization ...
...
int rc = sqlite3_open(dbFilename, &dbConnection);
if (rc != SQLITE_OK)
handleDbError(rc, dbConnection);
dbQueue = dispatch_queue_create("dbQueue", DISPATCH_QUEUE_SERIAL);
...
}
Here's how you use it:
dispatch_queue_async(dbQueue, ^{
// This block runs off the main thread, and does not run simultaneously
// with any other blocks submitted to `dbQueue`.
NSString *result = executeDatabaseQuery();
dispatch_queue_async(dispatch_get_main_queue(), ^{
// This block runs on the main thread.
[(MyAppDelegate *)[UIApplication delegate] presentResult:result];
});
});
Upvotes: 2