-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

On 11/15/2010 04:15 AM, Ruslan Mullakhmetov wrote:
> i need to get last insert id in multithreaded app.
> I use C API, actually some C++ wrap over it.
> if i execute query like " insert into tbl( filed ) VALUES ( 1 ); Select
> last_insert_rowid() as li;" would be it atomic? or  it anyway would suffer
> from threads?

As others mentioned the value returned is for the database handle.  There
are two ways you can address this.  One is to make each thread use its own
completely separate database handle.  Do some benchmarking if you think it
will affect overall performance of your program (unlikely) and you can do
some tuning such as shared cache mode.

The other thing is to use a transaction.  I do queries like this:

  begin;
    insert into tbl( filed ) VALUES ( 1 );
    Select last_insert_rowid() as li;
  commit;

Another issue you need to be careful with when threading is errors as the
SQLite error stuff is not thread safe.  SQLite records the error message
pointer against the database handle and the error API returns this pointer.
 Another thread could cause  different error code/message by the time you
get their values.  Also the pointer the API returns could become invalid by
the time you use it due to other thread activity, with the worst case being
that you crash if it now points to unmapped memory.

You need to structure your calls to SQLite APIs like this:

  sqlite3_mutex_enter(sqlite3_db_mutex(db));
  rc=sqlite3_.......;
  if (rc!=SQLITE && rc!=SQLITE_DONE && rc!=SQLITE_ROW)
    {
        copy sqlite3_errmsg(db) into a thread local buffer;
        copy code as well if you don't use rc;
    }
  sqlite3_mutex_leave(sqlite3_db_mutex(db));


On first discovering this issue several years ago I did campaign for the
SQLite semantics be changed so that the error code and string become thread
local just like errno and GetLastError are, but DRH didn't want to do this
because there *may* be code out using SQLite that does calls in one thread
and retrieves error information in a different one.

Roger
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.10 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/

iEYEARECAAYFAkzhWQYACgkQmOOfHg372QSn+QCcC+PdUdjCrfny6fucvY5q1D8W
FIUAn1vAgsVDw+NESBbwsA8ST9mFIzVC
=a1CE
-----END PGP SIGNATURE-----
_______________________________________________
sqlite-users mailing list
sqlite-users@sqlite.org
http://sqlite.org:8080/cgi-bin/mailman/listinfo/sqlite-users

Reply via email to