gpt4 book ai didi

Python多处理

转载 作者:太空狗 更新时间:2023-10-30 00:37:16 25 4
gpt4 key购买 nike

这个问题更多的是事实调查和思考过程,而不是面向代码的问题。

我有许多已编译的 C++ 程序,需要在不同的时间使用不同的参数运行。我正在考虑使用 Python 多处理从作业队列 (rabbitmq) 读取作业,然后将该作业提供给 C++ 程序运行(可能是子进程)。我正在查看多处理模块,因为它都将在双 Xeon 服务器上运行,所以我想充分利用我的服务器的多处理器能力。

Python 程序将是中央管理器,它会简单地从队列中读取作业,使用适当的 C++ 程序生成一个进程(或子进程?)来运行该作业,获取结果(子进程标准输出和标准错误),提供给它回调并将进程放回等待下一个作业运行的进程队列中。

首先,这听起来像是一个有效的策略吗?

其次,有没有类似的例子?

提前谢谢你。

最佳答案

The Python program would be the central manager and would simply read jobs from the que, spawn a process (or subprocess?) with the appropriate C++ program to run the job, get the results (subprocess stdout & stderr), feed that to a callback and put the process back in a que of processes waiting for the next job to run.

为此您不需要multiprocessing 模块。 multiprocessing 模块非常适合将 Python 函数作为单独的进程运行。要运行 C++ 程序并从标准输出读取结果,您只需要 subprocess 模块。队列可以是一个列表,当列表为非空时,您的 Python 程序将简单地循环。


但是,如果你想

  1. 生成多个工作进程
  2. 让他们从公共(public)队列中读取数据
  3. 使用队列中的参数生成 C++ 程序(并行)
  4. 使用C++程序的输出将新项目放入队列

然后你可以像这样用multiprocessing来做:

测试.py:

import multiprocessing as mp
import subprocess
import shlex

def worker(q):
while True:
# Get an argument from the queue
x=q.get()

# You might change this to run your C++ program
proc=subprocess.Popen(
shlex.split('test2.py {x}'.format(x=x)),stdout=subprocess.PIPE)
out,err=proc.communicate()

print('{name}: using argument {x} outputs {o}'.format(
x=x,name=mp.current_process().name,o=out))

q.task_done()

# Put a new argument into the queue
q.put(int(out))

def main():
q=mp.JoinableQueue()

# Put some initial values into the queue
for t in range(1,3):
q.put(t)

# Create and start a pool of worker processes
for i in range(3):
p=mp.Process(target=worker, args=(q,))
p.daemon=True
p.start()
q.join()
print "Finished!"

if __name__=='__main__':
main()

test2.py(C++ 程序的简单替代品):

import time
import sys

x=int(sys.argv[1])
time.sleep(0.5)
print(x+3)

运行 test.py 可能会产生如下结果:

Process-1: using argument 1 outputs 4
Process-3: using argument 3 outputs 6
Process-2: using argument 2 outputs 5
Process-3: using argument 6 outputs 9
Process-1: using argument 4 outputs 7
Process-2: using argument 5 outputs 8
Process-3: using argument 9 outputs 12
Process-1: using argument 7 outputs 10
Process-2: using argument 8 outputs 11
Process-1: using argument 10 outputs 13

请注意,右侧列中的数字被反馈到队列中,并(最终)用作 test2.py 的参数,并显示为左侧列中的数字.

关于Python多处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6440474/

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