我在我的 Flask 网站上使用 sqlite3 数据库,并且在每个数据库访问中我使用线程。锁定以避免内存竞争:
# one sync, one connection, one cursor for the entirety of the website
sync = threading.Lock()
connection = sqlite3.connect('db', check_same_thread = false)
cursor = connection.cursor()
#...
with sync:
cursor.execute(...) # just .execute(), i do not use .commit()
当我在本地主机上将它用作裸烧瓶服务器时,它工作得很好。即使当我向它发送大量请求时,每个请求都必须访问数据库(而且不是一次),它也不会中断。但是,当我将此代码提交到使用 Phusion Passenger 的网站托管服务时,它通常工作正常,但当我执行太多请求时,会导致一遍又一遍地出现
sqlite3.OperationalError: database is locked
。
我做错了什么?我使用了互斥体,为什么数据库被锁定?这与我只使用一个光标有关吗?
我检查了与 Phusion Passenger 相关的文档:
https://www.phusionpassenger.com/library/indepth/processes.html
问题是所有的worker都在不同的进程中运行。它不是多线程,而是多处理。
在 python 中,由于 GIL,我们经常使用进程而不是线程(https://realpython.com/python-gil/)
我建议您检查以下问题:https://stackoverflow.com/a/3172950/8054608