gpt4 book ai didi

python - 在X个并行子进程中执行一个python方法,其中x是可配置的

转载 作者:行者123 更新时间:2023-11-28 22:35:17 25 4
gpt4 key购买 nike

我不是 python 专家,我正在尝试实现主题中的功能。

我知道如何使用并行执行方法的功能。例如

def main():
run_in_parallel(A,B)

def A():
while True:
print("A")

def B():
while True:
print("B")

def run_in_parallel(*fns):
proc = []
for fn in fns:
p = Process(target=fn)
p.start()
proc.append(p)
for p in proc:
p.join()

if __name__ == '__main__':
main()

但我不知道如何在 10/20/100/... 并行子进程中执行方法 A。

我们将不胜感激。

最佳答案

你的意思是你想在并行子进程中运行函数 A 10/20/100... 次?如果是,那么您可以像这样创建 20 个子流程:

def main():
run_in_parallel(A, 20)

def A():
while True:
print("A")

def run_in_parallel(fn, proc_count):
proc = []
for _ in range(proc_count):
p = Process(target=fn)
p.start()
proc.append(p)
for p in proc:
p.join()

if __name__ == '__main__':
main()

关于python - 在X个并行子进程中执行一个python方法,其中x是可配置的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38300160/

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