如何通过多处理过程从函数运行中返回值

问题描述 投票:0回答:2

变量time_completed获得None,而目标是获得process函数完成的时间。如何确保时间返回parent

import time, multiprocessing

def process():
    num = int()
    while True:
        print '...sleeping %s' % num
        time.sleep(1)
        num += 1
        if num > 10:
            break
    return time.time() 


class Child(object):
    def __init__(self):
        super(Child, self).__init__()

    def process(self):
        proc = multiprocessing.Process(target=process)
        proc.start()

class Parent(object):
    def __init__(self):
        super(Parent, self).__init__()
        child = Child()
        time_completed = child.process()
        print 'time_completed: %s' % time_completed



obj = Parent()
python multiprocess
2个回答
1
投票

您可以使用Pipe或共享内存Value(或类似的Array)在进程之间进行通信。以下是使用Pipe的示例:

import multiprocessing as mp

def worker(p):
    msg = 'Hello from child!'
    print("sending {!r} to parent".format(msg))
    p.send(msg)
    v = p.recv()
    print("got {!r} from parent".format(v))

if __name__ == '__main__':
    p_conn, c_conn = mp.Pipe()
    p = mp.Process(target=worker, args=(c_conn,))
    p.start()
    msg = 'Hello from parent!'
    print("got {!r} from child".format(p_conn.recv()))
    print("sending {!r} to child".format(msg))
    p_conn.send(msg)
    p.join()

或者,你可以使用Pool,它最常见的情况是需要N令人尴尬的并行工作者,每个都有一个返回值。 (注意,我在这里使用multiprocess,这比multiprocessing更灵活 - 例如它在解释器中效果更好):

>>> import multiprocess as mp
>>> import time
>>> def process(n):
...     num = int()
...     while True:
...         print '...sleeping %s' % num
...         time.sleep(1)
...         num += 1
...         if num > 10:
...             break
...     return time.time() 
... 
>>> mp.Pool(2).map(process, [None]*2)
...sleeping 0
...sleeping 0
...sleeping 1
...sleeping 1
...sleeping 2
...sleeping 2
...sleeping 3
...sleeping 3
...sleeping 4
...sleeping 4
...sleeping 5
...sleeping 5
...sleeping 6
...sleeping 6
...sleeping 7
...sleeping 7
...sleeping 8
...sleeping 8
...sleeping 9
...sleeping 9
...sleeping 10
...sleeping 10
[1540486371.700522, 1540486371.700522]

0
投票

首先,您需要等待您的流程。例如,通过调用join。

其次,process()应该在Child中存储一个值,该值可以在之后访问并返回。

© www.soinside.com 2019 - 2024. All rights reserved.