【问题标题】:Multithreaded MySql Inserts with Python使用 Python 进行多线程 MySql 插入
【发布时间】:2011-04-01 18:25:07
【问题描述】:

下面是我用来上传数据到 MySQL 的多线程脚本。使用线程进行多次插入,对我来说听起来不错。

但是没有性能提升。 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 字符串设置在顶部。我试图在 Worker 线程中使用 cxn 字符串,但有很多改进。在工作线程中,MySQL 是单向的。表被截断然后插入。每个工人通常只有一张桌子。它的速度很快,而且系统是本地的。但我没有看到多重连接,我希望看到。

队列 = 30-400 个项目。

【问题讨论】:

    标签: python mysql multithreading


    【解决方案1】:

    您的队列中有多少项?

    所有操作都在同一张表上吗?如果是这样,如果由于表上的锁而选择和插入/更新/删除,多线程可能无济于事。

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

    如果有 25 个线程,您的线程也可能会争夺队列中的锁。

    【讨论】:

    • 是否也有可能因为他使用线程而不是多处理而遇到 GIL 问题?
    • 也许吧,但由于线程是 IO 绑定的,我不确定。也许 GIL 会导致问题,因为队列中的项目似乎是一个接一个地获取。
    • 在您的进程列表中您没有看到很多连接?你指的是哪个进程列表? ps,windows taks 管理器?
    • MySql 上的进程列表 -- 直接 cxn
    • 你创建了多个 MySql 连接,每个线程一个,对吧?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多