如何运行同时处理多个?

How to run multiple process simultaneously?

我有一个流程非常耗时的循环,而不是等待每个流程完成移动到下一次迭代,是否可以 运行 流程并直接移动到下一次迭代而不等待它完成了吗?

示例:给定一段文本,脚本应尝试从 Web 和本地磁盘中的文件中找到匹配的链接。 return 都是链接或路径的列表。

for proc in (web_search, file_search):
   results = proc(text)
   yield from results

我的解决方案是,在完成工作时使用计时器。如果时间超过了等待时间,则该过程应移至托盘并要求从那里开始工作。现在我将转到下一次迭代并重复相同的操作。在我的循环结束后,我将收集移动到托盘的过程的结果。

对于简单的情况,objective是让每个进程运行同时进行,我们可以使用threading模块的Thread。 所以我们可以这样解决这个问题,我们将每个进程作为一个 Thread 并要求它把它的结果放在一个列表或其他一些集合中。代码如下:

from threading import Thread

results = []

def add_to_collection(proc, args, collection):
    '''proc is the function, args are the arguments to pass to it.
       collection is our container (here it is the list results) for
       collecting results.'''
    result = proc(*args)
    collection.append(result)
    print("Completed":, proc)

# Now we do our time consuming tasks

for proc in (web_search, file_search):
    t = Thread(target=add_to_collection, args=(proc, ()))
    # We assume proc takes no arguments
    t.start()

对于复杂的任务,如评论中所述,最好使用multiprocessing.pool.Pool