我在与 sqlalchemy 一起使用的 InnoDB 表中遇到死锁的大问题。
sqlalchemy.exc.InternalError: (mysql.connector.errors.InternalError) 1213 (40001): 尝试获取锁时发现死锁;尝试重新启动事务。
我已经序列化了访问,但仍然出现死锁错误。
该代码在每个函数的第一次调用时执行。每个线程和进程都应该在这里等待,直到获得锁。它被简化了,因为选择器被删除了。
# The work with the index -1 always exists.
f = s.query(WorkerInProgress).with_for_update().filter(
WorkerInProgress.offset == -1).first()
Run Code Online (Sandbox Code Playgroud)
我已将代码减少到最小状态。我当前仅对 next_slice 方法运行并发调用。会话处理、回滚和死锁处理都是在外部处理的。
即使所有访问都是序列化的,我也会遇到死锁。我也尝试在 offset == -1 实体中增加重试计数器。
def next_slice(self, s, processgroup_id, itemcount):
f = s.query(WorkerInProgress).with_for_update().filter(
WorkerInProgress.offset == -1).first()
#Take first matching object if available / Maybe some workers failed
item = s.query(WorkerInProgress).with_for_update().filter(
WorkerInProgress.processgroup_id != processgroup_id,
WorkerInProgress.processgroup_id != 'finished',
WorkerInProgress.processgroup_id != 'finished!locked',
WorkerInProgress.offset != -1
).order_by(WorkerInProgress.offset.asc()).limit(1).first()
# *****
# Some code is missing …Run Code Online (Sandbox Code Playgroud)