生成函数的并行进程并将几个不同的参数传递给函数

Spawn parallel processes for function and pass several different arguments to function

大家好,我以 Jiaaro's solution 作为模板,将其从线程转换为多处理:

import multiprocessing
from function_repo import run
from time import time

vitems = ['02','63','25','0']

num_processes = (multiprocessing.cpu_count()/1)
threads = []

if __name__ == '__main__':
    begin = time()
    print begin
    # run until all the threads are done, and there is no data left
    while threads or vitems:
        if( len(threads) < (num_processes -1) ):

            p = multiprocessing.Process(target=run,args=[vitems.pop()])

            p.start()

            print p, p.is_alive()

            threads.append(p)

        else:

            for thread in threads:

                if not thread.is_alive():

                    threads.remove(thread)
    print  'Hello, finished'
    print  'Took: ',(time()-begin)

它工作得很好,但现在我想将第二个不是列表的参数传递给 run 函数,例如 p = multiprocessing.Process(target=run,args=([vitems.pop()],second_arg))

这会导致函数中断,因为如果我这样做,vitems 的完整列表会在每个进程中传递给函数。

我如何仍然只将每个进程的一项 vitems 传递给函数,并将第二个非列表参数传递给函数 run

在此先致谢并致以最诚挚的问候!

p = multiprocessing.Process(target=run, args=[vitems.pop()]) 不会将列表传递给 run,它会将从 vitems 弹出的项目作为第一个参数传递。 args 应该是传递给 run 的 list/tuple 个参数。

要传递多个参数,只需执行以下操作:

p = multiprocessing.Process(target=run, args=(vitems.pop(), arg2, ...))