SQLite Forum

set/get last_insert_rowid - To mutex or not mutex?
Login
The memory barrier issued when releasing the mutex will make sure that the
 (component) writes already executed by (and visible to) the CPU running the thread will be visible to any and all other CPUs. This will cause the subsequent read to be consistent, even if the thread is switched over to a different CPU before reading back the value.

If a different thread uses the connection, it may clobber the lastRowid variable anyway when it issues an INSERT (either directly or as the result of a virtual table implementation or a trigger program), so this situation is already a programming error (failing to retain control of the connection between setting and getting the lastRowid variable).

It just so happens that IF the underlying memory architecture supports less than 64bit atomic writes AND the (illegal) second thread is changing the lastRowid EXACTLY WHEN the first thread is retrieving its value, it is not predictable if the value retrieveid will be the old (first thread) value, the new (second thread) value or any mix of components because the threads are concurrently executing on two different CPUs.

The value returned to the first thread is already unreliable by virtue of having lost control of the connection, and may refer to an arbitrary table, so not returning a valid rowid sometimes is not a big deal IMHO