gpt4 book ai didi

python - 如何从多处理进程运行的函数返回值

转载 作者:行者123 更新时间:2023-12-01 01:29:59 26 4
gpt4 key购买 nike

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

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()

最佳答案

您可以使用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]

关于python - 如何从多处理进程运行的函数返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52980021/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com