从一个 Python 文件启动多个无限 Python 进程

假设我有三个模块:


模组1模组2模组3


一旦 mod.launch() 被调用,它们中的每一个都会无限长地运行。


有什么优雅的方法可以一次启动所有这些无限循环,而无需等待一个完成后再调用另一个?


假设我有一种launcher.py,我会尝试:


import mod1

import mod2

import mod3


if __name__ == "__main__":

    mod1.launch()

    mod2.launch()

    mod3.launch()

这显然不起作用,因为它会在启动 mod2.launch() 之前等待 mod1.launch() 完成。


任何形式的帮助表示赞赏。


POPMUISE
浏览 224回答 3
3回答

侃侃尔雅

如果您想并行执行多个函数,您可以使用multiprocessing库或concurrent.futures.ProcessPoolExecutor。ProcessPoolExecutor 在内部使用多处理,但具有更简单的接口。

慕码人2483693

根据每项任务中正在完成的工作的性质,答案会有所不同。如果每个任务大部分或全部都是 IO 绑定的,我会推荐多线程。如果每个任务都受 CPU 限制,我会推荐多处理(由于 Python 中的 GIL)。

胡说叔叔

我建议使用Ray,它是一个用于并行和分布式 Python 的库。与标准线程和多处理库相比,它具有一些优势。相同的代码将在单台机器或多台机器上运行。您可以并行化函数和类。使用共享内存在任务之间有效地共享对象。为了提供一个简单的可运行示例,我将使用函数和类而不是模块,但您始终可以将模块包装在函数或类中。方法一:并行函数使用任务。import rayimport timeray.init()@ray.remotedef mod1():    time.sleep(3)@ray.remotedef mod2():    time.sleep(3)@ray.remotedef mod3():    time.sleep(3)if __name__ == '__main__':    # Start the tasks. These will run in parallel.    result_id1 = mod1.remote()    result_id2 = mod2.remote()    result_id3 = mod3.remote()    # Don't exit the interpreter before the tasks have finished.    ray.get([result_id1, result_id2, result_id3])方法 2:使用actor 的并行类。import rayimport time# Don't run this again if you've already run it.ray.init()@ray.remoteclass Mod1(object):    def run(self):        time.sleep(3)@ray.remoteclass Mod2(object):    def run(self):        time.sleep(3)@ray.remoteclass Mod3(object):    def run(self):        time.sleep(3)if __name__ == '__main__':    # Create 3 actors.    mod1 = Mod1.remote()    mod2 = Mod2.remote()    mod3 = Mod3.remote()    # Start the methods, these will run in parallel.    result_id1 = mod1.run.remote()    result_id2 = mod2.run.remote()    result_id3 = mod3.run.remote()    # Don't exit the interpreter before the tasks have finished.    ray.get([result_id1, result_id2, result_id3])您可以查看Ray 文档。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python