[ZODB-Dev] How to update an object in a multithreading application?
Sebastian Wain
sebastian.wain at nektra.com
Mon Mar 19 17:04:34 UTC 2012
I am updating an item in a separated thread but when it finishes the new
value is not updated in the same object in the main thread.
In the example below root['counter'] starts in 0, is incremented in the new
thread but it remains in 0 in the main thread.
#!/usr/bin/python
from ZODB.FileStorage import FileStorage
from ZODB.DB import DB
from BTrees.OOBTree import OOBTree
import transaction
from threading import Thread
import persistent
class MyThread(Thread):
def __init__(self, db):
Thread.__init__(self)
self.db = db
def run(self):
self.connection = self.db.open(transaction.TransactionManager())
self.root = self.connection.root()
print "Starting thread"
self.connection.transaction_manager.begin()
self.root["counter"] += 1
self.connection.transaction_manager.commit()
print "self.root['counter'] =", self.root['counter']
filename = 'test.fs'
storage = FileStorage(filename)
db = DB(storage)
connection = db.open()
root = connection.root()
if 'counter' not in root:
transaction.begin()
root['counter'] = 0
transaction.commit()
thread = MyThread(db)
thread.start()
thread.join()
print "*** After ***"
print "root['counter'] =", root['counter']
Thanks,
Sebastian
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.zope.org/pipermail/zodb-dev/attachments/20120319/47c296e6/attachment.html>
More information about the ZODB-Dev
mailing list