Python3中的多处理并行处理和等待作业
我有一段查询DB并返回一组ID的代码。对于每个ID,我需要运行相关查询以获取数据集。我希望并行运行查询以加快处理速度。所有进程运行后,我构建一个文本块并将其写入文件,然后移动到下一个idPython3中的多处理并行处理和等待作业,python,multithreading,python-3.x,multiprocessing,Python,Multithreading,Python 3.x,Multiprocessing,我有一段查询DB并返回一组ID的代码。对于每个ID,我需要运行相关查询以获取数据集。我希望并行运行查询以加快处理速度。所有进程运行后,我构建一个文本块并将其写入文件,然后移动到下一个id 如何确保所有进程同时启动,然后等待所有进程完成,然后再转到页面=…和writefile操作 如果按原样运行,则会出现以下错误:进程对象不可编辑(第9行) 以下是我到目前为止的情况: from helpers import * import multiprocessing idSet = getIDset(10
页面=…
和writefile
操作进程对象不可编辑
(第9行)from helpers import *
import multiprocessing
idSet = getIDset(10)
for id in idSet:
ds1 = multiprocessing.Process(target = getDS1(id))
ds1list1, ds1Item1, ds1Item2 = (ds1)
ds2 = multiprocessing.Process(target = getDS2(id))
ds3 = multiprocessing.Process(target = getDS3(id))
ds4 = multiprocessing.Process(target = getDS4(id))
ds5 = multiprocessing.Process(target = getDS5(id))
movefiles = multiprocessing.Process(moveFiles(srcPath = r'Z://', src = ds1Item2 , dstPath=r'E:/new_data_dump//'))
## is there a better way to get them to start in unison than this?
ds1.start()
ds2.start()
ds3.start()
ds4.start()
ds5.start()
## how do I know all processes are finished before moving on?
page = +ds1+'\n' \
+ds2+'\n' \
+ds3+'\n' \
+ds4+'\n' \
+ds5+'\n'
writeFile(r'E:/new_data_dump/',filename+'.txt',page)
我通常把我的“过程”列在一个列表中
plist = []
for i in range(0, 5) :
p = multiprocessing.Process(target = getDS2(id))
plist.append(p)
for p in plist :
p.start()
... do stuff ...
for p in plist :
p.join() # <---- this will wait for each process to finish before continuing
其中target是函数,args是按如下方式传递的arguemnt的元组:
def f(name) :
print name
非常感谢。将进程行的格式更改为
(target=function,args=(id,)
)似乎确实在推进进程。但是,我不明白如何从函数中获取返回值。例如:process(target=getDS2,args(id,)
…getDS2(id)
返回我需要处理的数据块。如果我太密集,很抱歉。进程之间的通信是另一个问题。您无法使用进程直接获取返回值。好的,因此,我处理了队列的返回问题。不幸的是,其中一个函数返回的数据集对于QUU来说太大e、 所以,整件事并没有真正起作用。谢谢@beiller,你的信息帮了大忙。我们说的队列太大是不是太大了?试着把它写到一个文件中,或者把文件名写到一个队列中。谢谢@beiller-测试用例大约有50k个字符。我从我读到的其他东西中怀疑它可能太大了,但是,我想我会的尝试一下。将其写入文件可能有效,但我必须进行另一个操作以将该文件与其他文件合并。。。
def f(name) :
print name