2
下面是我用來上傳數據到MySQL的多線程腳本。使用線程來做多個插入,聽起來不錯。多線程MySql插入Python
但是沒有性能收益。 MySql被設置爲接受多連接,但是當我檢查進程列表時,我沒有看到我期望的5-10個連接。 cxn字符串是
有什麼辦法可以解決這個問題嗎?
import sys, threading, Queue pyodbc
class WorkerThread(threading.Thread):
def __init__(self, queue):
threading.Thread.__init__(self)
self.queue = queue
def run(self):
while 1:
try: # take a job from the queue
id, null, null2, null3 = self.queue.get_nowait()
except Queue.Empty:
raise SystemExit
In Here I have MySQl connecctions
*** cxn = pyodbc.connect('DSN=MySQL;PWD=MLML;Option=3')
csr = cxn.cursor()
typical insert , selects Updates
if __name__ == '__main__':
connections = 25
# build a queue with tuples
queue = Queue.Queue()
queue.put(row[:3])
# print queue
threads = []
for dummy in range(connections):
t = WorkerThread(queue)
t.start()
threads.append(t)
# wait for all threads to finish
for thread in threads:
thread.join()
Cxn String置於頂部。我曾嘗試在Worker線程中使用cxn字符串,但那裏有很多改進。在工作者線程中,MySQL是單向的。表格被截斷然後插入。通常每個工人只有一張桌子。它的速度很快,而且系統是本地的。但我沒有看到mutli連接,我期望看到。
隊列= 30-400項。
也有可能是因爲他使用線程而不是多處理,他遇到了與GIL的問題? – 2011-04-01 18:59:05
也許,但由於線程是IO綁定的,我不確定。由於物品似乎在隊列中被逐一取出,所以GIL可能會引發問題。 – Martin 2011-04-01 19:04:09
增加了一些以上 – Merlin 2011-04-01 19:18:42