我有一个 Python 3 程序,它根据行的 ID(在 Postgres 9.5 数据库的表中)更新大量行。
我使用多处理来加速这个过程。由于 Psycopg 的连接不能跨进程共享,我为每一行创建一个连接,然后关闭它。
总体而言,多处理比单处理快(8 个 CPU 快 5 倍)。但是,创建连接的速度很慢:我只想创建几个连接并根据需要保持打开状态。
由于 .map() 将 ids_list 分成许多提交给进程池的 block ,是否可以为同一 block /进程中的所有 ID 共享一个数据库连接?
示例代码:
from multiprocessing import Pool
import psycopg2
def create_db_connection():
conn = psycopg2.connect(database=database,
user=user,
password=password,
host=host)
return conn
def my_function(item_id):
conn = create_db_connection()
# Other CPU-intensive operations are done here
cur = conn.cursor()
cur.execute("""
UPDATE table
SET
my_column = 1
WHERE id = %s;
""",
(item_id, ))
cur.close()
conn.commit()
if __name__ == '__main__':
ids_list = [] # Long list of ids
pool = Pool() # os.cpu_count() processes
pool.map(my_function, ids_list)
感谢您提供的任何帮助。
最佳答案
您可以使用 Pool 构造函数的 initializer 参数。 在初始化函数中设置数据库连接。也许将连接凭据作为参数传递。
查看文档:https://docs.python.org/3/library/multiprocessing.html#module-multiprocessing.pool
关于python - 在进程池中共享数据库连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40064437/