问题描述
我正在使用 SQLAlchemy、python 和多线程编写程序.
I am writing a program using SQLAlchemy, python, and multithreading.
在我的设计中,线程 A 使用 while True 循环.在每个循环中,它通过 SQLAlchemy 从数据库中获取查询的对象,然后检查对象的一个字段.如果满足条件,则中断while循环.数据库中记录的字段将由线程 B 更新.
In my design, Thread A uses a while True loop. In each loop, it gets the queried object from database by SQLAlchemy, then check a field of the object. If it meets the condition, break the while loop. The field of the record in database will be updated by Thread 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值.然而,线程A一直在while循环中等待,并没有中断.
The result turned out that the record in the database has been updated by Thread-B to the break-condition value of the while loop in Thread-A. However, Thread-A keeps waiting in the while loop and did not break.
有人可以提供一些见解吗?
Could someone give some insight?
谢谢!
推荐答案
这是由事务的孤立性质造成的
This cause by the isolated nature of transactions
具有平均隔离度的事务将保持其迄今为止加载的状态,并继续为您提供事务本地的相同状态,即使实际数据已更改 - 这在事务隔离中称为可重复读取说法.
这篇关于为什么一个线程无法检测到另一个线程更新的更改值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!