On 04/09/14 06:59, Neo Anderson wrote: > I'm building a custom library wrapper for Cocoa. I want to handle database > threading issue myself.
One gotcha not documented in the threading pages is that the SQLite error handling APIs are not threadsafe, and the only correct way of handling errors with SQLite is your own extra layer of locking. (Every app I've looked at just hopes for the best and gets lucky.) The root cause is that the SQLite error code and string are per database. They are *not* as is the case with errno/GetLastError per thread. Consequently any access or changes to them can race with other threads. It can even cause your app to crash or use junk memory. To safely do multithreaded error handling you need to do the following: 1 - acquire a lock protecting the database (eg sqlite3_db_mutex) 2 - call the relevant SQLite APIs for your operation 3 - if there was an error code/message then copy them somewhere else 4 - release the lock As an example of how to get junk/crash leave out step 1 and 4. Step 3 gets you an error code (which could be for a different database operation on the same database handle different thread) and a pointer to an error message. In the time between getting the message pointer, and actually doing something with it, a different thread could have deallocated the pointer and replaced with a new one. The now deallocated one could point to junk (will strlen terminate before running out of address space?) or even now unmapped memory. Roger _______________________________________________ sqlite-users mailing list sqlite-users@sqlite.org http://sqlite.org:8080/cgi-bin/mailman/listinfo/sqlite-users