gpt4 book ai didi

python - 在python中为多个文件并行运行相同的函数

转载 作者:行者123 更新时间:2023-11-28 19:49:04 42 4
gpt4 key购买 nike

我正在尝试为多个文件并行运行一个函数,并希望所有文件都在一个点之前终止。

例如:有一个循环

def main():
for item in list:
function_x(item)

function_y(list)

现在我想要的是这个 function_x 应该对所有项目并行运行。但是在调用我的 function_y 之前,应该为所有项目执行此函数。

我打算为此使用 celery 。但不明白如何做到这一点。

最佳答案

这是我最终的测试代码。

我需要做的就是使用多处理库。

from multiprocessing import Process
from time import sleep

Pros = []

def function_x(i):
for j in range(0,5):
sleep(3)
print i

def function_y():
print "done"

def main():
for i in range(0,3):
print "Thread Started"
p = Process(target=function_x, args=(i,))
Pros.append(p)
p.start()

# block until all the threads finish (i.e. block until all function_x calls finish)
for t in Pros:
t.join()

function_y()

关于python - 在python中为多个文件并行运行相同的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25889268/

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