[英]sqlobject thread safety
我的python腳本讀取並遞增行屬性。 我從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()函數中使用threading.Lock()進行序列化,但我想避免它。
有關env的其他信息:底層數據庫是MySql,python 2.7,sqlobject ver 1.5
谷歌搜索后找到了答案:
它以前不適合我,因為底層的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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.