How to use SQLite in a multi-threaded application?

前端 未结 7 1009
情书的邮戳
情书的邮戳 2020-11-28 02:43

I\'m developing an application with SQLite as the database, and am having a little trouble understanding how to go about using it in multiple threads (none of the other Stac

7条回答
  •  孤街浪徒
    2020-11-28 03:18

    Some steps when starting out with SQLlite for multithreaded use:

    1. Make sure sqlite is compiled with the multi threaded flag.
    2. You must call open on your sqlite file to create a connection on each thread, don't share connections between threads.
    3. SQLite has a very conservative threading model, when you do a write operation, which includes opening transactions that are about to do an INSERT/UPDATE/DELETE, other threads will be blocked until this operation completes.
    4. If you don't use a transaction, then transactions are implicit, so if you start a INSERT/DELETE/UPDATE, sqlite will try to acquire an exclusive lock, and complete the operation before releasing it.
    5. If you do a BEGIN EXCLUSIVE statement, it will acquire an exclusive lock before doing operations in that transaction. A COMMIT or ROLLBACK will release the lock.
    6. Your sqlite3_step, sqlite3_prepare and some other calls may return SQLITE_BUSY or SQLITE_LOCKED. SQLITE_BUSY usually means that sqlite needs to acquire the lock. The biggest difference between the two return values:
      • SQLITE_LOCKED: if you get this from a sqlite3_step statement, you MUST call sqlite3_reset on the statement handle. You should only get this on the first call to sqlite3_step, so once reset is called you can actually "retry" your sqlite3_step call. On other operations, it's the same as SQLITE_BUSY
      • SQLITE_BUSY : There is no need to call sqlite3_reset, just retry your operation after waiting a bit for the lock to be released.

提交回复
热议问题