Python多处理 - 子进程不断发回结果并继续运行
问题描述:
有可能有几个子进程运行一些计算,然后将结果发送到主进程(例如,更新PyQt ui),但进程仍在运行他们发回数据并再次更新ui? 使用multiprocessing.queue时,似乎数据只能在进程终止后才发回。 所以我想知道这种情况是否可能。提前致谢!Python多处理 - 子进程不断发回结果并继续运行
答
我不知道你的意思是“使用multiprocessing.queue,它似乎只能在进程终止后发回数据”。这正是Multiprocessing.Queue设计的用例。
PyMOTW是整个Python模块负载(包括多处理)的绝佳资源。看看这里:https://pymotw.com/2/multiprocessing/communication.html
如何从一个孩子正在发送消息给使用多和循环家长一个简单的例子:
import multiprocessing
def child_process(q):
for i in range(10):
q.put(i)
q.put("done") # tell the parent process we've finished
def parent_process():
q = multiprocessing.Queue()
child = multiprocessing.Process(target=child_process, args=(q,))
child.start()
while True:
value = q.get()
if value == "done": # no more values from child process
break
print value
# do other stuff, child will continue to run in separate process
我不知道我的理解。你的意思是如果完成需要超过一定的时间,你想终止这个过程?如果这是你想要的,那么你应该看看信号包中的signal.alarm https://docs.python.org/2/library/signal.html – wolfson109
谢谢!所以我想知道一个情况,如果我想从子进程得到一些结果而不等待它终止。子进程始终运行并不断发送数据。那可能吗? – nmvhs
是的,你只需要在每次产生一个新值时调用queue.put的循环中运行你的子进程。然后父线程可以运行一个不同的循环,每次都调用queue.get。 – wolfson109