SQLAlchemy / MySQL 序列化访问上的死锁

ego*_*ot0 6 python mysql deadlock sqlalchemy

我在与 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 here. as it's not executed in my testcase

    # Fetch the latest item and add a new one 
    item = s.query(WorkerInProgress).with_for_update().order_by(
        WorkerInProgress.offset.desc()).limit(1).first()     

    new = WorkerInProgress()
    new.offset = item.offset + item.count
    new.count = itemcount
    new.maxtries = 3
    new.processgroup_id = processgroup_id
    s.add(new)
    s.commit()
    return new.offset, new.count
Run Code Online (Sandbox Code Playgroud)

我不明白为什么会发生僵局。

我通过在一个查询中获取所有项目来减少死锁,但仍然会出现死锁。也许有人可以帮助我。

ego*_*ot0 6

最后我解决了我的问题。这些都在文档中,但我必须先理解它。

如果交易因死锁而失败,请始终做好重新发出交易的准备。死锁并不危险。再试一次。

来源:http ://dev.mysql.com/doc/refman/5.7/en/innodb-deadlocks-handling.html

我通过改变这部分的架构解决了我的问题。我仍然遇到很多死锁,但它们几乎出现在短时间运行的方法中。我已将工作表分为锁定部分和非锁定部分。锁定部分的操作现在非常短,并且在 get_slice、finish_slice 和fail_slice 操作期间不处理任何数据。

具有数据处理的事务部分现在处于非锁定部分,并且没有对表行的并发访问。结果存储在finish_slice和fail_slice中到锁定表中。

最后我在 stackoverflow 上也找到了一个很好的描述。确定正确的搜索词后。 /sf/answers/181727101/