I am writing a program using SQLAlchemy, python, and multithreading.
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.
My Thread-A code:
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'
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?
Thanks!