sqlite3.dylib: illegal multi-threaded access to database connection

后端 未结 4 1640
[愿得一人]
[愿得一人] 2021-01-02 08:40

I have an iOS app that uses sqlite3 and I\'m facing issues with multi-threading crashing the app with the illegal multi-threaded access to database connec

4条回答
  •  感动是毒
    2021-01-02 09:24

    It turns out that SQLITE_CONFIG_MULTITHREAD mode works well on a multi-threading environment as long as you don't use the same connection simultaneously; which happen to be the exact scenario that I had. Therefore, to solve this issue you can either open a new connection for each thread or use SQLITE_CONFIG_SERIALIZED in full mutex mode using SQLITE_OPEN_FULLMUTEX flag to open the connection.

    The helper method ended up like so:

    +(sqlite3*) getInstance {
      if (instance == NULL) {
        sqlite3_shutdown();
        sqlite3_config(SQLITE_CONFIG_SERIALIZED);
        sqlite3_initialize();
    
        NSLog(@"isThreadSafe %d", sqlite3_threadsafe());
    
        const char *path = [@"./path/to/db/db.sqlite" cStringUsingEncoding:NSUTF8StringEncoding];
    
        if (sqlite3_open_v2(path, &database, SQLITE_OPEN_READWRITE|SQLITE_OPEN_FULLMUTEX, NULL) != SQLITE_OK) {
          NSLog(@"Database opening failed!");
        }
      }
    
      return instance;
    }
    

提交回复
热议问题