首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >sqlobject线程安全

sqlobject线程安全
EN

Stack Overflow用户
提问于 2014-03-14 18:08:34
回答 1查看 248关注 0票数 3

我的python脚本读取并增加了一个row属性。我从4个不同的线程调用这个函数。

代码语言:javascript
复制
 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

EN

回答 1

Stack Overflow用户

发布于 2014-03-18 09:45:27

在谷歌上搜索了很多之后找到了答案:

因为底层的mysql表使用的是MyISAM引擎而不是InnoDB引擎,所以它以前不适用于我。MyISAM不支持事务和行级锁定。

代码语言:javascript
复制
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()
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22412669

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档