When an user starts my app, I want to first download some data from the internet to synch with the sqlite database in the phone. I do this in another thread. I know sqlite is not thread-safe, so instead of updating the database in the 2nd thread, I plan to return the the main thread, and update the database there.
Will this prevent any concurrency issues with updating the sqlite db if I choose to do it this way? Will there be any other issues I should be aware of?
Example:
dispatch_async(dispatch_get_global_queue(0, 0), ^{
//downloading data...
dispatch_async(dispatch_get_main_queue(), ^{
//update database here
}
}
Usually SQLite is compiled to be technically thread-safe — access from multiple threads will not result in corruption of the database or erroneous behavior of the SQLite code.
However, when you access a SQLite database simultaneously from multiple threads, the “loser” threads will likely get a “Database locked” error. You can handle this by delaying briefly and then retrying the operation, or you can implement a separate lock protocol around database accesses.
If you can somehow arrange to perform all accesses from the same thread, “Database locked” errors should not occur, and the SQLite DB should be “happy”. However, keep in mind that “long-running” operations should not be performed in the main/UI thread, so you should not, in the main thread, dispatch complex queries or operate on large numbers of records in one operation.