代码之家  ›  专栏  ›  技术社区  ›  alphanumeric

如何从多进程运行的函数返回值

  •  0
  • alphanumeric  · 技术社区  · 6 年前

    变量 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()
    
    2 回复  |  直到 6 年前
        1
  •  2
  •   Mike McKerns    6 年前

    你可以使用 Pipe Value (或类似地) Array ),以便在进程之间进行通信。下面是一个使用 管道

    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]
    
        2
  •  0
  •   FFF    6 年前

    首先,您需要等待您的进程。

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

    推荐文章