Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLite database is getting locked

I have a piece of code in C++ that creates many threads & each of these threads access a common SQLite database & SELECTs & INSERTs data.

All the INSERTs are with in transactions. Many times I get "Database is locked" error.

How can I fix this?

like image 844
omggs Avatar asked Jan 16 '26 22:01

omggs


2 Answers

You can use SQLite in a multithreaded way, but for each thread you must open a new connection (sqlite3_open()) and operate on that connection.

There is more info in the official documentation

like image 116
Vinicius Kamakura Avatar answered Jan 19 '26 16:01

Vinicius Kamakura


If you start your transactions only with "BEGIN" on more than one thread and you are then using INSERTs sqlite can deadlock.

That's because sqlite only aquires a read lock on BEGIN. On the INSERT it has to upgrade that read lock to a write lock (which it can only do if there is no read lock). This does not happen with journal_mode=WAL (only the default journal_mode=delete) as wal mode allows read access during writes. (So using WAL mode might be a fix).

Solution: Use BEGIN IMMEDIATE if you plan to use an insert in a transaction. That way sqlite aquires a write lock on the database.

like image 25
UrOni Avatar answered Jan 19 '26 14:01

UrOni



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!