On May 21, 2008, at 12:08 PM, Shawn Wilsher wrote:

> Hey all,
> I've come to the sad realization that we need to make our sqlite
> wrapper threadsafe so it can be used on multiple threads without
> consumers having to worry about threadsafety themselves.  So, I wanted
> to make sure all my assumptions about sqlite data structures are
> correct so I don't introduce issues before undertaking this task.
> First, I know that the sqlite3 object can be accessed on multiple
> threads, but it must only be used by one thread of control at a time.

Beginning with version 3.5.0, SQLite enforces this itself using its  
own internal mutexes, so the application is free to (try to) use the  
same database connection from multiple threads at the same time.

> It is also my understanding that this same constraint applies to
> sqlite3_stmt objects - they can only be used by one thread of control
> at a time but accessed on multiple ones.  What I am not so sure about,
> however, is if I have to protect the sqlite3 object that "owns" the
> statement when I'm calling methods on it such as sqlite3_bind_*
> interfaces, sqlite3_step, sqlite3_reset, and sqlite3_finalize.
> Conservatively, I'm assuming yes on all of the above, but I hope I'm
> wrong for at least some of those.  I would, however, expect to have to
> protect the sqlite3 object when calling sqlite3_prepare_v2.
> Clarification on this would be greatly appreciated.

SQLite takes care of the serialization for you now.

There are a few routines that might not be purely threadsafe.  For  
example, sqlite3_last_insert_rowid().  All this does it return a 64- 
bit integer out of a structure.  But if a 64-bit integer load is not  
an atomic operation on your platform and a different thread happens to  
be updating the last_insert_rowid at the same time you are reading it,  
you might get back a nonsense value.  But on the other hand, if you  
have one thread trying to find the last_insert_rowid while another  
thread is busy changes the last_insert_rowid, then you already have  
bigger problems.  There are a few similar cases.

Of course, all this mutexing comes at a cost in performance.  When  
version 3.6.0 comes out, it might support a "low-mutex" mode as a  
compile-time option where it is the applications responsibility to  
serialize access to separate database connections again, just like in  

D. Richard Hipp

sqlite-users mailing list

Reply via email to