SQLite multi process access

后端 未结 3 1301
南笙
南笙 2021-02-09 04:32

We are using SQLite in a multi processes and multi threaded application. The SQLite database files are encrypted using the embedded SQLite encryption. The FAQ states that SQLite

3条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-09 04:51

    While SQLite is "thread-safe" you still can't concurrently modify the database:

    Each thread then proceeds to insert a number of records, let's say 1000. The problem you will encounter is the following: one thread will get control over the database by setting a lock on the file. This is fine, but the rest of the threads will keep on failing for each attempted INSERT while the lock is active. (reference)

    Only one thread is allowed to modify the database at a time, but you can have multiple threads that attempt to modify the database.

    If you want to avoid the failing-while-locked issue you can check the SQLITE_BUSY flag:

    Test for SQLITE_BUSY, which I didn't do originally. Here's some pseudo-code to illustrate a solution:

      while (continueTrying) {
        retval = sqlite_exec(db, sqlQuery, callback, 0, &msg);
        switch (retval) {
          case SQLITE_BUSY:
            Log("[%s] SQLITE_BUSY: sleeping fow a while...", threadName);
            sleep a bit... (use something like sleep(), for example)
            break;
          case SQLITE_OK:
            continueTrying = NO; // We're done
            break;
          default:
            Log("[%s] Can't execute \"%s\": %s\n", threadName, sqlQuery, msg);
            continueTrying = NO;
            break;
        }
      }
    
      return retval;
    

    same reference

    My bet is that your constraint violation has nothing to do with multithreading, so could you please post the actual constraint violation that you're getting (or an example that complies with www.sscce.org).

提交回复
热议问题