I have a script that includes opening a file from a list and then doing something to the text within that file. I’m using python multiprocessing and Pool to try to parallelize this operation. A abstraction of the script is below:
import os
from multiprocessing import Pool
results = []
def testFunc(files):
for file in files:
print "Working in Process #%d" % (os.getpid())
#This is just an illustration of some logic. This is not what I'm actually doing.
for line in file:
if 'dog' in line:
results.append(line)
if __name__=="__main__":
p = Pool(processes=2)
files = ['/path/to/file1.txt', '/path/to/file2.txt']
results = p.apply_async(testFunc, args = (files,))
results2 = results.get()
When I run this the print out of the process id is the same for each iteration. Basically what I’m trying to do is take each element of the input list and fork it out to a separate process, but it seems like one process is doing all of the work.
apply_asyncfarms out one task to the pool. You would need to callapply_asyncmany times to exercise more processors.results. Since the pool workers are separate processes, the twowon’t be writing to the same list. One way to work around this is to use an ouput Queue. You could set it up yourself, or use
apply_async‘s callback to setup the Queue for you.apply_asyncwill call the callback once the function completes.map_asyncinstead ofapply_async, but then you’dget a list of lists, which you’d then have to flatten.
So, perhaps try instead something like: