简体   繁体   English

使用python多处理从进程获取结果

[英]Obtain results from processes using python multiprocessing

I am trying to understand how to use the multiprocessing module in Python. 我试图了解如何在Python中使用多处理模块。 The code below spawns four processes and outputs the results as they become available. 下面的代码产生四个进程,并在结果可用时输出结果。 It seems to me that there must be a better way for how the results are obtained from the Queue; 在我看来,必须有一个更好的方法来从队列中获得结果; some method that does not rely on counting how many items the Queue contains but that just returns items as they become available and then gracefully exits once the queue is empty. 某些方法不依赖于计算Queue包含的项目数,而只是在项目可用时返回项目,然后在队列为空时正常退出。 The docs say that Queue.empty() method is not reliable. 文档说Queue.empty()方法不可靠。 Is there a better alternative for how to consume the results from the queue? 有没有更好的替代方法来消耗队列中的结果?

import multiprocessing as mp
import time


def multby4_wq(x, queue):
    print "Starting!"
    time.sleep(5.0/x)
    a = x*4
    queue.put(a)


if __name__ == '__main__':
    queue1 = mp.Queue()
    for i in range(1, 5):
        p = mp.Process(target=multbyc_wq, args=(i, queue1))
        p.start()
    for i in range(1, 5): # This is what I am referring to as counting again
        print queue1.get()

Instead of using queue, how about using Pool ? 而不是使用队列,如何使用

For example, 例如,

import multiprocessing as mp
import time


def multby4_wq(x):
    print "Starting!"
    time.sleep(5.0/x)
    a = x*4
    return a

if __name__ == '__main__':
    pool = mp.Pool(4)
    for result in pool.map(multby4_wq, range(1, 5)):
        print result

Pass multiple arguments 传递多个参数

Assume you have a function that accept multiple parameters ( add in this example). 假设您有一个接受多个参数的函数(在此示例中add )。 Make a wrapper function that pass arguments to add ( add_wrapper ). 创建一个包装函数,将参数传递给addadd_wrapper )。

import multiprocessing as mp
import time


def add(x, y):
    time.sleep(1)
    return x + y

def add_wrapper(args):
    return add(*args)

if __name__ == '__main__':
    pool = mp.Pool(4)
    for result in pool.map(add_wrapper, [(1,2), (3,4), (5,6), (7,8)]):
        print result

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM