我正在使用SQLAlchemy,python和多线程编写程序。
在我的设计中,线程A使用while True循环。在每个循环中,它通过SQLAlchemy从数据库中获取查询的对象,然后检查对象的字段。如果满足条件,请中断while循环。数据库中记录的字段将由线程B更新。
我的Thread-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'
结果表明,线程B将数据库中的记录更新为线程A中while循环的中断条件值。但是,线程A一直在while循环中等待并且没有中断。
有人可以提供一些见识吗?
谢谢!
答案 0 :(得分:1)
这是由于交易的孤立性所致
平均隔离度的事务将保持其到目前为止已加载的状态,并且即使真实数据已更改,也会一直为您提供该事务本地的相同状态-这称为事务隔离中的可重复读取措辞。