繁体   English   中英

多线程python psycopg2

[英]multi thread python psycopg2

我在python程序中使用多线程。 我有3个队列。 在其中之一中,我正在将数据插入postgres数据库。 但是之前,我需要检查数据库中是否已经存在具有特定域名的行。 所以我有:

class AnotherThread(threading.Thread):
    def __init__(self, another_queue):
        threading.Thread.__init__(self)
        self.another_queue = another_queue


    def run(self):
        while True:
            chunk = self.another_queue.get()
            if chunk is not '':
                dane = chunk[0].split(',',2)

                cur.execute("SELECT exists(SELECT 1 FROM global where domain = %s ) ", (domena,))
                jest = cur.fetchone()
                print(jest)

这是我的第三个队列的代码的一部分。 我在这里连接数据库(在main()函数中):

queue = Queue.Queue()
out_queue = Queue.Queue()
another_queue = Queue.Queue()

for i in range(50):
    t = ThreadUrl(queue, out_queue)
    t.setDaemon(True)
    t.start()

for host in hosts:
    queue.put(host)

for i in range(50):
    dt = DatamineThread(out_queue,another_queue)
    dt.setDaemon(True)
    dt.start()

conn_str = "dbname='{db}' user='user' host='localhost' password='pass'"
conn = psycopg2.connect(conn_str.format(db='test'))
conn.autocommit = True
cur = conn.cursor()

for i in range(50):
    dt = AnotherThread(another_queue)
    dt.setDaemon(True)
    dt.start()



queue.join()
out_queue.join()
another_queue.join()

cur.close()
conn.close()

运行脚本时,我得到:

(False,)
(False,)
(False,)
(False,)
(False,)
(False,)
(False,)
(False,)
(False,)
Exception in thread Thread-128:
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner
    self.run()
  File "domains.py", line 242, in run
    jest = cur.fetchone()
ProgrammingError: no results to fetch

Exception in thread Thread-127:
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner
    self.run()
  File "domains.py", line 242, in run
    jest = cur.fetchone()
ProgrammingError: no results to fetch

(False,)
(False,)
(False,)

为什么对于其中一些我却出错了?

这可能与所有线程共享相同的连接和游标的事实有关。 我能想象在那里的情况下cur.execute()运行,然后cur.fetchone()被另一个线程,然后cur.fetchone()再次(另一个或相同或以前)线程,没有cur.execute在之间。 Python GIL将在每行线程之间切换(声明)。 因此,第二次运行fetchone() ,不再有任何结果:最初只需要获取一行,现在已经用尽了。
您可能想隔离每个游标,或以某种方式使cur.execute(...); cur.fetchone() cur.execute(...); cur.fetchone()命令原子。


该问题的答案是在PostgreSQL中通过psycopg2在每个游标或每个连接 (DBA StackExchange链接)中进行的事务都提到了每个连接的事务,因此隔离游标可能对您没有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM