首页 > 解决方案 > 为什么一个线程无法检测到另一个线程更新的更改值?

问题描述

我正在使用 SQLAlchemy、python 和多线程编写程序。

在我的设计中,线程 A 使用了一个 while True 循环。在每个循环中,它通过 SQLAlchemy 从数据库中获取查询的对象,然后检查对象的一个​​字段。如果满足条件,则中断while循环。数据库中记录的字段将由线程 B 更新。

我的线程-A 代码:

    engine = create_engine('postgresql://postgres:passw0rd@localhost:5432/mini_amazon')
    Session = sessionmaker(bind=engine, expire_on_commit=False)

    @contextmanager
    def session_scope():
        """
        Provide a transactional scope around a series of operations.
        """
        session = Session()
        try:
            yield session
            session.commit()
        except:
            session.rollback()
            raise
        finally:
            session.close()

    with session_scope() as session:
        while True:
            print('Waiting')
            order = session.query(models.Order).get(arrived_message.packageid)
            time.sleep(1)
            if order.status == 'packed':
                break

        order.status = 'loading'

结果发现,数据库中的记录已经被 Thread-B 更新为 Thread-A 中 while 循环的 break-condition 值。但是,Thread-A 一直在 while 循环中等待并且没有中断。

有人可以提供一些见解吗?

谢谢!

标签: pythonormsqlalchemy

解决方案


这是由交易的孤立性质引起的

具有平均隔离度的事务将保持它迄今为止加载的状态,并继续为您提供与事务本地相同的状态,即使实际数据已更改 - 这在事务隔离用语中称为可重复读取。

如何禁用 SQLAlchemy 缓存?


推荐阅读