3 回答

TA贡献1801条经验 获得超16个赞
如果您想并行执行多个函数,您可以使用multiprocessing库或concurrent.futures.ProcessPoolExecutor。ProcessPoolExecutor 在内部使用多处理,但具有更简单的接口。

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

TA贡献1804条经验 获得超8个赞
我建议使用Ray,它是一个用于并行和分布式 Python 的库。与标准线程和多处理库相比,它具有一些优势。
相同的代码将在单台机器或多台机器上运行。
您可以并行化函数和类。
使用共享内存在任务之间有效地共享对象。
为了提供一个简单的可运行示例,我将使用函数和类而不是模块,但您始终可以将模块包装在函数或类中。
方法一:并行函数使用任务。
import ray
import time
ray.init()
@ray.remote
def mod1():
time.sleep(3)
@ray.remote
def mod2():
time.sleep(3)
@ray.remote
def 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 ray
import time
# Don't run this again if you've already run it.
ray.init()
@ray.remote
class Mod1(object):
def run(self):
time.sleep(3)
@ray.remote
class Mod2(object):
def run(self):
time.sleep(3)
@ray.remote
class 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 文档。
添加回答
举报