我的python脚本读取并增加了一个row属性。我从4个不同的线程调用这个函数。
def update_row():
row = myTable.select(myTable.q.id==1, forUpdate=True)[0]
row.count += 1
print "thread %s updated count to %s" %(threading.currentThread(),row.count)
th1 = threading.Thread(target=update_row, )
th2 = threading.Thread(target=update_row, )
th3 = threading.Thread(target=update_row, )
th4 = threading.Thread(target=update_row, )
print "Before starting threads count=",myTable.get(1).count
th1.start()
th2.start()
th3.start()
th4.start()在几次运行中,我注意到计数值并不总是增加4。
我的问题:sqlobject中是否有任何机制(除了forUpdate之外,它似乎对我不起作用)使同一个对象线程上的更新操作变得安全?
我知道我可以简单地在update_row()函数中使用update_row()来进行序列化,但我想避免它。
关于env的其他信息:基础数据库是MySql,python2.7,sqlobject ver1.5
发布于 2014-03-18 09:45:27
在谷歌上搜索了很多之后找到了答案:
因为底层的mysql表使用的是MyISAM引擎而不是InnoDB引擎,所以它以前不适用于我。MyISAM不支持事务和行级锁定。
def update_row():
try:
trans = conn.transaction()
row = myTable.select(myTable.q.id==1, connection=trans, forUpdate=True)[0]
print "thread %s select done:"%threading.currentThread(),row.count
row.count += 1
print "thread %s updated count:"%threading.currentThread(),row.count
except Exception, fault:
print str(fault)
trans.rollback()
else:
trans.commit()https://stackoverflow.com/questions/22412669
复制相似问题