如何恢复传递给multiprocessing.Process的函数的返回值?

时间:2012-05-02 13:44:35

标签: python python-multiprocessing

在下面的示例代码中,我想恢复函数worker的返回值。我该怎么做呢?这个值存储在哪里?

示例代码:

import multiprocessing

def worker(procnum):
    '''worker function'''
    print str(procnum) + ' represent!'
    return procnum


if __name__ == '__main__':
    jobs = []
    for i in range(5):
        p = multiprocessing.Process(target=worker, args=(i,))
        jobs.append(p)
        p.start()

    for proc in jobs:
        proc.join()
    print jobs

输出:

0 represent!
1 represent!
2 represent!
3 represent!
4 represent!
[<Process(Process-1, stopped)>, <Process(Process-2, stopped)>, <Process(Process-3, stopped)>, <Process(Process-4, stopped)>, <Process(Process-5, stopped)>]

我似乎无法在jobs中存储的对象中找到相关属性。

提前致谢, BLZ

12 个答案:

答案 0 :(得分:117)

使用shared variable进行通信。例如:

import multiprocessing

def worker(procnum, return_dict):
    '''worker function'''
    print str(procnum) + ' represent!'
    return_dict[procnum] = procnum


if __name__ == '__main__':
    manager = multiprocessing.Manager()
    return_dict = manager.dict()
    jobs = []
    for i in range(5):
        p = multiprocessing.Process(target=worker, args=(i,return_dict))
        jobs.append(p)
        p.start()

    for proc in jobs:
        proc.join()
    print return_dict.values()

答案 1 :(得分:51)

我认为@sega_sai建议的方法更好。但它确实需要一个代码示例,所以这里是:

import multiprocessing
from os import getpid

def worker(procnum):
    print 'I am number %d in process %d' % (procnum, getpid())
    return getpid()

if __name__ == '__main__':
    pool = multiprocessing.Pool(processes = 3)
    print pool.map(worker, range(5))

将打印返回值:

I am number 0 in process 19139
I am number 1 in process 19138
I am number 2 in process 19140
I am number 3 in process 19139
I am number 4 in process 19140
[19139, 19138, 19140, 19139, 19140]

如果您熟悉map(内置Python 2),这应该不会太具挑战性。否则请查看sega_Sai's link

请注意需要的代码很少。 (还要注意如何重复使用进程)。

答案 2 :(得分:16)

此示例显示如何使用multiprocessing.Pipe实例列表从任意数量的进程返回字符串:

import multiprocessing

def worker(procnum, send_end):
    '''worker function'''
    result = str(procnum) + ' represent!'
    print result
    send_end.send(result)

def main():
    jobs = []
    pipe_list = []
    for i in range(5):
        recv_end, send_end = multiprocessing.Pipe(False)
        p = multiprocessing.Process(target=worker, args=(i, send_end))
        jobs.append(p)
        pipe_list.append(recv_end)
        p.start()

    for proc in jobs:
        proc.join()
    result_list = [x.recv() for x in pipe_list]
    print result_list

if __name__ == '__main__':
    main()

<强>输出:

0 represent!
1 represent!
2 represent!
3 represent!
4 represent!
['0 represent!', '1 represent!', '2 represent!', '3 represent!', '4 represent!']

此解决方案使用的资源少于使用

multiprocessing.Queue
  • a Pipe
  • 至少一个锁
  • 缓冲区
  • 一个帖子

或使用

multiprocessing.SimpleQueue
  • a Pipe
  • 至少一个锁

查看每种类型的来源非常有启发性。

答案 3 :(得分:10)

您似乎应该使用multiprocessing.Pool类并使用方法.apply()。apply_async(),map()

http://docs.python.org/library/multiprocessing.html?highlight=pool#multiprocessing.pool.AsyncResult

答案 4 :(得分:10)

对于正在寻求如何使用ProcessQueue获取价值的其他人:

import multiprocessing

ret = {'foo': False}

def worker(queue):
    ret = queue.get()
    ret['foo'] = True
    queue.put(ret)

if __name__ == '__main__':
    queue = multiprocessing.Queue()
    queue.put(ret)
    p = multiprocessing.Process(target=worker, args=(queue,))
    p.start()
    print queue.get()  # Prints {"foo": True}
    p.join()

答案 5 :(得分:9)

您可以使用内置的exit来设置流程的退出代码。它可以从流程的exitcode属性中获取:

import multiprocessing

def worker(procnum):
    print str(procnum) + ' represent!'
    exit(procnum)

if __name__ == '__main__':
    jobs = []
    for i in range(5):
        p = multiprocessing.Process(target=worker, args=(i,))
        jobs.append(p)
        p.start()

    result = []
    for proc in jobs:
        proc.join()
        result.append(proc.exitcode)
    print result

<强>输出:

0 represent!
1 represent!
2 represent!
3 represent!
4 represent!
[0, 1, 2, 3, 4]

答案 6 :(得分:9)

出于某种原因,我无法找到一个如何使用Queue在任何地方执行此操作的一般示例(即使Python的doc示例也不会产生多个进程),所以这就是我在10次尝试后工作的内容:

def add_helper(queue, arg1, arg2): # the func called in child processes
    ret = arg1 + arg2
    queue.put(ret)

def multi_add(): # spawns child processes
    q = Queue()
    processes = []
    rets = []
    for _ in range(0, 100):
        p = Process(target=add_helper, args=(q, 1, 2))
        processes.append(p)
        p.start()
    for p in processes:
        ret = q.get() # will block
        rets.append(ret)
    for p in processes:
        p.join()
    return rets

Queue是一个阻塞的,线程安全的队列,可用于存储子进程的返回值。所以你必须将队列传递给每个进程。这里不太明显的是,在get() join之前你必须从队列中Process,否则队列会填满并阻止所有事情。

那些面向对象的人(在Python 3.4中测试)

更新

from multiprocessing import Process, Queue

class Multiprocessor():

    def __init__(self):
        self.processes = []
        self.queue = Queue()

    @staticmethod
    def _wrapper(func, queue, args, kwargs):
        ret = func(*args, **kwargs)
        queue.put(ret)

    def run(self, func, *args, **kwargs):
        args2 = [func, self.queue, args, kwargs]
        p = Process(target=self._wrapper, args=args2)
        self.processes.append(p)
        p.start()

    def wait(self):
        rets = []
        for p in self.processes:
            ret = self.queue.get()
            rets.append(ret)
        for p in self.processes:
            p.join()
        return rets

# tester
if __name__ == "__main__":
    mp = Multiprocessor()
    num_proc = 64
    for _ in range(num_proc): # queue up multiple tasks running `sum`
        mp.run(sum, [1, 2, 3, 4, 5])
    ret = mp.wait() # get all results
    print(ret)
    assert len(ret) == num_proc and all(r == 15 for r in ret)

答案 7 :(得分:2)

如果您使用的是Python 3,则可以使用concurrent.futures.ProcessPoolExecutor作为便捷的抽象方法:

<com.google.android.material.textfield.TextInputLayout
                            android:layout_width="0dip"
                            android:layout_weight="0.4"
                            android:id="@+id/tilFPCode"
                            app:errorTextAppearance="@style/style_EditText_ErrorStyle"
                            app:hintTextAppearance="@style/style_EditText_HintStyle"
                            android:layout_height="wrap_content">

                        <com.google.android.material.textfield.TextInputEditText
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:maxLines="1"
                                android:maxLength="5"
                                android:id="@+id/etFPCode"
                                android:imeOptions="actionDone"
                                android:inputType="textCapCharacters"
                                android:textAllCaps="true"
                                android:hint="@string/forgot_sec_code_hint"
                                style="@style/style_EditText"/>

                    </com.google.android.material.textfield.TextInputLayout>

输出:

from concurrent.futures import ProcessPoolExecutor

def worker(procnum):
    '''worker function'''
    print(str(procnum) + ' represent!')
    return procnum


if __name__ == '__main__':
    with ProcessPoolExecutor() as executor:
        print(list(executor.map(worker, range(5))))

答案 8 :(得分:1)

pebble软件包利用multiprocessing.Pipe有一个很好的抽象,这使得这一过程非常简单:

from pebble import concurrent

@concurrent.process
def function(arg, kwarg=0):
    return arg + kwarg

future = function(1, kwarg=1)

print(future.result())

示例来自:https://pythonhosted.org/Pebble/#concurrent-decorators

答案 9 :(得分:1)

我想简化从上面复制的最简单的示例,在Py3.6上为我工作。最简单的是multiprocessing.Pool

import multiprocessing
import time

def worker(x):
    time.sleep(1)
    return x

pool = multiprocessing.Pool()
print(pool.map(worker, range(10)))

您可以使用Pool(processes=5)来设置池中的进程数。但是,它默认为CPU计数,因此对于CPU绑定任务,将其留空。 (无论如何,受I / O约束的任务通常无论如何都适合线程,因为线程大多在等待,因此可以共享一个CPU内核。)Pool也适用于chunking optimization

(请注意,worker方法不能嵌套在方法中。我最初在对pool.map进行调用的方法内定义了worker方法,以使其全部独立,但随后这些进程无法t导入它,并抛出“ AttributeError:无法腌制本地对象external_method..inner_method”。更多here。它可以在一个类中。)


Py3的ProcessPoolExecutor也是两行(.map返回一个生成器,因此您需要list()):

from concurrent.futures import ProcessPoolExecutor
with ProcessPoolExecutor() as executor:
    print(list(executor.map(worker, range(10))))

使用普通的Process是:

import multiprocessing
import time

def worker(x, queue):
    time.sleep(1)
    queue.put(x)

queue = multiprocessing.SimpleQueue()
tasks = range(10)

for task in tasks:
    multiprocessing.Process(target=worker, args=(task, queue,)).start()

for _ in tasks:
    print(queue.get())

如果您只需要putget,请使用SimpleQueue。第一个循环开始所有进程,然后第二个循环进行阻塞的queue.get调用。我认为也没有任何理由致电p.join()

答案 10 :(得分:0)

我修改了vartec的答案,因为我需要从函数中获取错误代码。 (谢谢椎骨!它是一个很棒的技巧)

这也可以使用manager.list完成,但我认为最好将它放在dict中并在其中存储列表。这样,我们保持功能和结果的方式,因为我们无法确定列表的填充顺序。

from multiprocessing import Process
import time
import datetime
import multiprocessing


def func1(fn, m_list):
    print 'func1: starting'
    time.sleep(1)
    m_list[fn] = "this is the first function"
    print 'func1: finishing'
    # return "func1"  # no need for return since Multiprocess doesnt return it =(

def func2(fn, m_list):
    print 'func2: starting'
    time.sleep(3)
    m_list[fn] = "this is function 2"
    print 'func2: finishing'
    # return "func2"

def func3(fn, m_list):
    print 'func3: starting'
    time.sleep(9)
    # if fail wont join the rest because it never populate the dict
    # or do a try/except to get something in return.
    raise ValueError("failed here")
    # if we want to get the error in the manager dict we can catch the error
    try:
        raise ValueError("failed here")
        m_list[fn] = "this is third"
    except:
        m_list[fn] = "this is third and it fail horrible"
        # print 'func3: finishing'
        # return "func3"


def runInParallel(*fns):  # * is to accept any input in list
    start_time = datetime.datetime.now()
    proc = []
    manager = multiprocessing.Manager()
    m_list = manager.dict()
    for fn in fns:
        # print fn
        # print dir(fn)
        p = Process(target=fn, name=fn.func_name, args=(fn, m_list))
        p.start()
        proc.append(p)
    for p in proc:
        p.join()  # 5 is the time out

    print datetime.datetime.now() - start_time
    return m_list, proc

if __name__ == '__main__':
    manager, proc = runInParallel(func1, func2, func3)
    # print dir(proc[0])
    # print proc[0]._name
    # print proc[0].name
    # print proc[0].exitcode

    # here you can check what did fail
    for i in proc:
        print i.name, i.exitcode  # name was set up in the Process line 53

    # here will only show the function that worked and where able to populate the 
    # manager dict
    for i, j in manager.items():
        print dir(i)  # things you can do to the function
        print i, j

答案 11 :(得分:0)

一个简单的解决方案:

import multiprocessing

output=[]
data = range(0,10)

def f(x):
    return x**2

def handler():
    p = multiprocessing.Pool(64)
    r=p.map(f, data)
    return r

if __name__ == '__main__':
    output.append(handler())

print(output[0])

输出:

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]