【问题标题】:Python multithreading in a loop for executing query sql用于执行查询 sql 的循环中的 Python 多线程
【发布时间】:2017-11-02 17:06:36
【问题描述】:

我想在多线程中转换我的程序,但我没有说该怎么做。确实,我想到了 2 个解决方案,但我认为这不是最理想的: 在 python 中进行选择并将结果存储在数组中,然后按线程范围过滤。 或带有子句 id 的多线程,选择只有一个 Domain by thread 有没有更好的方法可以直接在循环中进行?

#!/usr/bin/python
import mysql.connector as mariadb
from subprocess import Popen, PIPE, STDOUT
import re
import os

mariadb_connection = mariadb.connect(user='root', password='xxxx', database='xxxx');
cursor = mariadb_connection.cursor(buffered=True)
#retrieving information

cursor.execute("SELECT Domain,Id FROM classement where Domain like '%com';")

for Domain,Id in cursor:
          counter=0
          for character in Domain:
                if (character == "."):
                        counter = counter + 1
                        if (counter==1):
                            print(Domain)
                            pingresult = Popen(['ping','-c','3', Domain], stdout=PIPE, stderr=STDOUT).communicate()[0]
                            pingresult=str(pingresult)
                            ping = pingresult.find('min/avg/max/mdev')
                            ping=pingresult[ping+19:-6]
                            print(ping)
                            cursor.execute('update classement set Ping = "%s" where Domain = "%s";' % (ping,Domain))
                            mariadb_connection.commit()
mariadb_connection.close()

【问题讨论】:

    标签: python multithreading python-multiprocessing


    【解决方案1】:

    我认为最简单的方法是将循环包装在函数中并使用multiprocessing.dummy 线程池:

    from multiprocessing.dummy import Pool
    ...
    cursor.execute( ... )
    ...
    
    def process (entry):
        Domain,Id = entry
        ...
        # your code there
        ...
        cursor.execute( ... )
        mariadb_connection.commit()
    
    pool = Pool(os.cpu_count())
    # or may be N*os.cpu_count() if ping waits for
    # network interaction too long
    
    pool.map(process, cursor)
    pool.join()
    

    多线程访问数据库可能需要额外的锁定。

    【讨论】:

    • 感谢您的回答,但我不明白,因为如果我并行化光标,执行的查询是相同的,但由多个线程执行,所以我不会提高速度吗?
    • 主要问题是你的程序有瓶颈吗?如果它在popen - 是的,不同线程中的多个 ping 将提高执行速度。如果在将结果插入数据库时​​遇到瓶颈,首先不要在每次查询后执行commit。多次插入操作后尝试提交。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-12
    • 2021-02-02
    相关资源
    最近更新 更多