[英]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.