python / multiprocessing:如何简化“def”字段

时间:2013-07-12 22:17:55

标签: python multiprocessing function

下面的脚本只使用多处理从0到9计数,其中Thread-1计算偶数,Thread-2计算偶数。请注意,工作者本身的唯一区别是初始x值为0和1.有没有办法简化此操作而不是一遍又一遍地键入相同的代码?对于2个线程来说并不是一件大事,但是对于每个不同的起始值,有16个进程(0-16),这非常多余。

#!/usr/bin/python
from multiprocessing import Process

def worker1(name):
    x = 0
    print name, 'starting...'
    while x < 10:
            print x
            x+=2
    print name, 'complete!'

def worker2(name):
    x = 1
    print name, 'starting...'
    while x < 10:
            print x
            x+=2
    print name, 'complete!'


if __name__ == '__main__':
    wa = Process(target=worker1, args=('Thread-1',))
    wb = Process(target=worker2, args=('Thread-2',))

    wa.start()
    wb.start()

2 个答案:

答案 0 :(得分:2)

x作为参数传递给worker

import multiprocessing as mp

def worker(x):
    name = mp.current_process().name
    print name, 'starting...'
    while x < 10:
            print x
            x+=2
    print name, 'complete!'

if __name__ == '__main__':
    num_procs = 2
    procs = [mp.Process(target=worker, args=(x,)) for x in range(num_procs)]
    for proc in procs:
        proc.start()
    for proc in procs:
        proc.join()

您不必将name作为参数传递; multiprocessing为每个流程提供了mp.current_process().name可访问的名称。如果您确实需要自定义名称,请使用mp.Process(target=worker, name='custom name', ...)设置名称。然后,可以使用worker`mp.current_process().name内访问自定义名称。

答案 1 :(得分:2)

您可以将初始值以及步骤和其他变量传递给worker:

#!/usr/bin/python
from multiprocessing import Process

def worker(name, initial, step=2):
    x = initial
    print name, 'starting...'
    while x < 10:
            print x
            x += step
    print name, 'complete!'

if __name__ == '__main__':
    wa = Process(target=worker1, args=('Thread-1', 0))
    wb = Process(target=worker2, args=('Thread-2', 1))

    wa.start()
    wb.start()