我正在尝试异步处理多个文件,并且处理每个文件都需要对 SQLite 数据库进行一些读写操作。我一直在寻找一些选项,我找到了 aiosqlite 模块 here .但是,我正在阅读 SQLite 文档 here ,并说它支持多线程模式。实际上,默认模式是“序列化”,这意味着它“可以不受限制地被多个线程安全使用”。
我不明白有什么区别。 aiosqlite 文档说:
aiosqlite allows interaction with SQLite databases on the main AsyncIO event loop without blocking execution of other coroutines while waiting for queries or data fetches. It does this by using a single, shared thread per connection.
我知道 aiosqlite 和 sqlite 上的“多线程”模式之间存在差异,因为多线程模式每个线程只需要一个连接,而在 aiosqlite 中,您可以跨多个线程重用这个单一连接。但这与可以“被多个线程无限制地使用”的序列化模式不一样吗?
编辑:我现在的问题是“我目前的理解是否正确?”:
threading
python中的模块并产生了多个线程。在这里,我可以选择每个线程使用单独的连接或跨多个线程共享连接。 最佳答案
首先关于线程:
Sqlite ... can be used by multiple threads at one time
由于GIL,它仍然不会同时出现。 , 线程总是同时运行(不是并行)。使用 GIL 的唯一一件事是您不知道线程何时会被中断。但是 asyncio 允许您“手动”在线程之间切换并等待一些 IO 操作(如数据库通信)。
让我解释一下不同模式之间的区别:
在更新中回答问题:
Sqlite in "serialized" mode can be used by multiple threads at one time, so this would be used if I used the threading module in python and spawned multiple threads. Here I have the options of either using a separate connection per thread or sharing the connection across multiple threads.
aiosqlite is used with asyncio. So since asyncio has multiple coroutines that share one thread, aiosqlite also works with one thread. So I create one connection that I share among all the coroutines
Since aiosqlite is basically a wrapper for sqlite, I can combine the functionality of 1 and 2. So I can have multiple threads where each thread has an asyncio event loop with multiple coroutines. So the basic sqlite functionality will handle the multi-threading and the aiosqlite will handle the coroutines.
关于python - 多线程模式下的 aiosqlite 和 SQLite 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63813922/