I’ve stuck with this SQLAlchemy-Python problem: here’s a class that should do simple update job in multiple threads
class InThreadUpdater():
def __init__(self):
self.portion_size = 5
self.select_portion_func = db.session.query(FBPostStats).with_lockmode("update").limit(self.portion_size)
def run(self):
for post in self.select_portion_func.all():
post.locked_by_thread = True
db.session.commit()
if __name__ == "__main__":
updater = InThreadUpdater()
thread = threading.Thread(target=updater.run)
But after finish there’s no real changes committed to db. It works if I move initialization of
member select_portion_func to function run() like this
def run(self):
self.select_portion_func = db.session.query(FBPostStats).with_lockmode("update").limit(self.portion_size)
for post in self.select_portion_func.all():
post.locked_by_thread = True
db.session.commit()
What’s the difference between these two variants? Why the first gives some kind of copy for post?
Thanks in advance!
Because it is actually a copy – when new thread is created,
updatervariable is copied into another memory region in the heap on the new thread. This is probably a bad idea to share db-connections in such a way.