python - 为什么一个线程无法检测到另一个线程更新的更改值?
问题描述
我正在使用 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 循环中等待并且没有中断。
有人可以提供一些见解吗?
谢谢!
解决方案
这是由交易的孤立性质引起的
具有平均隔离度的事务将保持它迄今为止加载的状态,并继续为您提供与事务本地相同的状态,即使实际数据已更改 - 这在事务隔离用语中称为可重复读取。
推荐阅读
- android - 如何全屏打开侧边导航
- html - 如何制作带有标签a的下拉菜单?
- javascript - 根据条件将数组的元素替换为另一个数组的元素
- ruby - 如何使用 Ruby fiddle 加载 Windows DLL 文件?
- bash - 通过编辑相同的变量来设置变量
- swift - 是否可以以编程方式更新在函数中更新的 UILabel 文本,然后通过选择器调用该文本?
- neo4j - 计数集合时计数不正确
- typescript - 数组查找方法错误元素隐式具有“任何”类型
- php - 如何从我需要在控制器中的 CodeIgniter 中的配置文件中获取变量
- python - 一个类的结果如何在另一个类中使用