2011-04-01 56 views
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项。

回答

1

您的队列中有多少物品?

所有的操作都在同一张桌子上吗?如果是这样,如果由于表上的锁定而选择并插入/更新/删除,则多线程可能无法帮助。

从您的例子中,我们看不到您创建连接的位置。它是在每个线程中创建的,还是对所有线程使用相同的连接?

使用25个线程,您的线程可能也在争夺队列上的锁定。

+0

也有可能是因为他使用线程而不是多处理,他遇到了与GIL的问题? – 2011-04-01 18:59:05

+0

也许,但由于线程是IO绑定的,我不确定。由于物品似乎在队列中被逐一取出,所以GIL可能会引发问题。 – Martin 2011-04-01 19:04:09

+0

增加了一些以上 – Merlin 2011-04-01 19:18:42