代码之家  ›  专栏  ›  技术社区  ›  Richard Levasseur

Python中的cx_Oracle、生成器和线程

  •  4
  • Richard Levasseur  · 技术社区  · 16 年前

    当连接对象被不同的线程使用时,cx_Oracle游标的行为是什么?生成器将如何影响此行为?明确地

    编辑 :原始示例函数不正确;一个子函数正在返回一个生成器, yield 没有直接在循环中使用。这澄清了什么时候 finally 被执行(之后) return 但是仍然没有回答如果另一个线程开始使用创建游标的连接对象时是否可以使用游标。实际上看起来(至少在python 2.4中), try...finally 产量 导致语法错误。

    def Get()
      conn = pool.get()
      try:
        cursor = conn.cursor()
        cursor.execute("select * from table ...")
        return IterRows(cursor)
      finally:
        pool.put(conn)
    
    def IterRows(cursor):
      for r in cursor:
        yield r
    

    Get() 是由多个线程调用的函数。这些连接是使用 threaded=False

    我想知道。。。

    1. 是线程1的吗 cursor 如果线程2出现并使用相同的连接对象,对象仍然可用吗?如果没有,会发生什么?

    1 回复  |  直到 16 年前
        1
  •  2
  •   maxschlepzig    9 年前

    the docs : threadsafety 是,我引述,

    目前为2,这意味着 可以共享模块和连接, 但不是游标。

    螺纹安全 水平。这不是共享连接的问题(这没关系,因为你已经通过了 threaded threading.local

    写下你的问题2,答案是 finally 子句在生成器对象(通过调用生成器函数生成)时执行 Get StopIteration

    def imthecaller():
      for i, row in enumerate(Get()):
        print i, row
        if i > 1: break
      # this is the moment the generators' finally-clause runs
      print 'bye'
    

    这个 在(最多)3行完成后执行 yield