Does thread-safety of SQLite3 mean different threads can modify the same table of a database concurrently?
4 回答
否 - SQLite 不支持对同一数据库文件的并发写访问。SQLite 将简单地阻止其中一个事务,直到另一个事务完成。
请注意,如果您使用的是 python,要从不同的线程访问 sqlite3 连接,您需要禁用该check_same_thread
参数,例如:
sqlite.connect(":memory:", check_same_thread = False)
截至 2010 年 5 月 24 日,文档省略了此选项。遗漏在这里被列为错误
Not necessarily. If sqlite3 is compiled with the thread safe macro (check via the
int sqlite3_threadsafe(void)function), then you can try to access the same DB from multiple threads without the risk of corruption. Depending on the lock(s) required, however, you may or may not be able to actually modify data (I don't believe sqlite3 supports row locking, which means that to write, you'll need to get a table lock). However, you can try; if one threads blocks, then it will automatically write as soon as the other thread finishes with the DB.
您可以在 3 种不同的模式下使用 SQLite:
http://www.sqlite.org/threadsafe.html
如果您决定采用多线程模式或序列化模式,您可以轻松地在多线程应用程序中使用 SQLite。在这些情况下,无论如何您都可以同时读取所有线程。如果您需要同时写入,打开的表将自动锁定当前写入线程并在此之后解锁(下一个线程将等待(互斥)轮到他,直到表被解锁)。在所有这些情况下,您需要为每个线程 (.NET Data.Sqlite.dll) 创建单独的连接字符串。如果您使用其他实现(例如任何 Android 包装器),有时情况会有所不同。