Reputation: 452
I'm trying to write a multithreaded (using NSOperationQueues for writes and executing reads on the main thread) application to access sqlite database data. I understand that sqlite isn't threadsafe by default, but we've added the multithreaded preprocessor macro and set our journaling mode to wal.
According to this sqlite documentation: http://www.sqlite.org/faq.html#q6 it seems we need to finalize all of our prepared statements before writing anything. Is this true? Is there any way to avoid this? What if we have two handles to the same database?
Basically we want to have multiple reads and a single write going on at one time but are trying to figure out the best way.
Thanks in advance.
Upvotes: 1
Views: 1718
Reputation: 39306
The threading mode is determined by compile time, startup or runtime options. More details here:
http://www.sqlite.org/threadsafe.html
The docs say serialized is the default which means you're fine to use from multiple threads - it will guard you with all access being serialized. If you want more parallelism, you can use multi-threaded mode with multiple connection objects.
If you use multi-threaded, ensure the same db connection object is not used by more than one thread at any one point in time:
Multi-thread. In this mode, SQLite can be safely used by multiple threads provided that no single database connection is used simultaneously in two or more threads.
But, make sure the complexity is justified. As with all performance issues, measure before and after.
EDIT: one way to ensure this is to create your own pooling mechanism. Create a pool of n connection handles that each parallel tasks gets and releases to the pool. The docs say that multi-threaded mode is completely safe across connections. That way, you don't have to worry about all other transactions or statements being finalized. A separate read thread/connection and write thread/connection is effectively a very simple hardcoded pool.
Upvotes: 2