Multithreaded SQLite Crash

I am trying to use SQLite 3.7.5 in a multithreaded C ++ program. I narrowed it down to a few simple lines of code:

sqlite3 *Database; sqlite3_stmt *Stmt; int retval=sqlite3_open("database.db3",&Database); retVal=sqlite3_prepare(&Database,"CREATE TABLE RawData (Key CHAR(5))",-1,&Stmt,0); retval=sqlite3_step(Stmt); retval=sqlite3_finalize(Stmt); 

When I call this code directly from my main process, it works fine. However, if I use CreateThread () to create a thread:

 unsigned long ThreadId; CreateThread(0,0,(LPTHREAD_START_ROUTINE) InserterThread,&Info,0,&ThreadId); 

I get a Visual Buffer Forwarding message in sqlite3_step call. If I debug, I see that the location of the failure is in _CRT_DEBUGGER_HOOK in the dbghook.c file.

I use the multi-threaded Static VC libraries and compile with define:

 SQLITE_THREADSAFE=2 THREADSAFE=2 

I checked with sqlite3_threadsafe () .

I can track the SQLite 3 code a bit, but I hope someone finds an obvious problem with my code and saves me.

+4
source share
1 answer

It seems that SQLITE_THREADSAFE is defined for compilation, they do not make the library work, just make it available.

You still need to tell sqlite that you want multithreaded behavior, either at database startup or at runtime.

Select a stream mode in start mode

Assuming that the compilation stream processing mode is not single-threaded, the initialization mode can be changed using the sqlite3_config () interface. Verb SQLITE_CONFIG_SINGLETHREAD SQLite in single-threaded mode, SQLITE_CONFIG_MULTITHREAD verb sets multithreaded mode, and the set of verbs SQLITE_CONFIG_SERIALIZED serialized mode.

Runtime mode selection

If single-threaded mode was not selected during compilation or the start time, then individual database connections can be created as either multi-threaded or serialized. It is not possible to reduce individual database connection to single-threaded mode. And this is not so possible escalation of a separate database connection if the compilation or start time is single-threaded.

The streaming mode for a separate connection to the database is determined by the flags specified as the third argument to sqlite3_open_v2 (). The SQLITE_OPEN_NOMUTEX flag causes the database connection to be in multithreaded mode, and the SQLITE_OPEN_FULLMUTEX flag causes the connection to be in serialized mode. If no flag is specified, or if sqlite3_open () or sqlite3_open16 () is used instead of sqlite3_open_v2 (), then the default mode is determined by compile time and start time.

Link http://www.sqlite.org/threadsafe.html

+3
source

Source: https://habr.com/ru/post/1392146/


All Articles