在python中并行运行多个文件的相同功能

Gau*_*ngh 2 python celery

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

例如:有一个循环

def main():
  对于列表中的项目:
     function_x(item)

  function_y(清单)

现在我想要的是,这个function_x应该对所有项目并行运行。但是在我的function_y被调用之前,所有项目都应完成此功能。 我打算为此使用芹菜。但是不知道该怎么做。

Gau*_*ngh 6

这是我的最终测试代码。

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

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()
Run Code Online (Sandbox Code Playgroud)


Eli*_*sha 5

您可以为此使用线程。thread.join是你需要的函数,这个函数会阻塞直到线程完成。
你可以这样做:

import threading
threads = []
def main():
  for item in list:
     t = threading.Thread(target=function_x, args=(item,))
     threads.append(t)
     t.start()

  # block until all the threads finish (i.e. until all function_a functions finish)    
  for t in threads:
     t.join()

  function_y(list)
Run Code Online (Sandbox Code Playgroud)