我们有一个小型的python程序,该程序可以对不断填充的目录中的文件进行排序,并将其相应地加载到正确的MySQL表中。
有七个表,并且python程序每个表维护5个打开的连接(使用名为DBUtils.PooledDB的工具)。
我想通过所有35(7x5)个连接并行发送文件,但是使用map的python多处理使我能够在一个级别(到一个表的五个连接)上进行发送,但是父进程必须串行运行(通过七个表)。
我使用multiprocessing.Pool.map_async()启动整个过程,因此开始时所有35个连接均处于活动状态,但是当每个表结束时,其余表必须等待整个池完成。 / p>
我希望能够分别运行所有35个进程,以便它们可以继续彼此独立地工作。
from multiprocessing import Pool
import pymysql
from DBUtils.PooledDB import PooledDB
# Pool of 35 connections
g_pool_0 = PooledDB(creator=pymysql, maxconnections=5 host=host, user=user db=db)
...
g_pool_6 = PooledDB(creator=pymysql, maxconnections=5 host=host, user=user db=db)
def insert_to_db(filename):
# Load filename data into the database according to the filename
if __name__ == "__main__":
while True:
files_0 = glob.glob(join(cur_d, 'results/*_0.csv'))
...
files_0 = glob.glob(join(cur_d, 'results/*_6.csv'))
# start inserting to DB on all 7 databases
pool_0 = Pool(5)
pool_0.map_async(insert_to_db, files_0)
...
pool_7 = Pool(5)
pool_7.map_async(insert_to_db, files_7)
pool_0.close()
pool_0.join()
...
pool_7.close()
pool_7.join()
这有效,但是我必须使用while循环来继续处理接收恒定文件流的目录。如果while循环中有任何活动的连接,则其他连接必须等待while循环结束。
我不想运行7个单独的脚本。无论如何,在嵌套线程/进程中可以做到这一点吗?