【问题标题】:multi thread python psycopg2多线程 python psycopg2
【发布时间】:2018-02-06 04:20:24
【问题描述】:

我在 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,)

为什么其中一些我收到错误消息?

【问题讨论】:

    标签: python multithreading postgresql psycopg2


    【解决方案1】:

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


    are transactions in postgresql via psycopg2 per cursor or per connection(DBA StackExchange 链接)问题的答案提到事务是每个连接的,因此隔离游标可能对您没有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 2017-03-22
      • 2018-06-26
      • 2023-03-08
      • 2022-01-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多