【问题标题】:Spawn parallel processes for function and pass several different arguments to function为函数生成并行进程并将几个不同的参数传递给函数
【发布时间】:2015-08-20 05:05:15
【问题描述】:

大家好,我以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

提前致谢并致以最诚挚的问候!

【问题讨论】:

    标签: python multiprocessing python-multiprocessing


    【解决方案1】:

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

    要传递多个参数,只需这样做:

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

    【讨论】:

      猜你喜欢
      • 2021-04-13
      • 2017-05-07
      • 2018-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-27
      • 2018-06-03
      • 1970-01-01
      相关资源
      最近更新 更多