【问题标题】:Python: CPU intensive tasks on multiple threadsPython:多线程上的 CPU 密集型任务
【发布时间】:2020-10-11 04:26:12
【问题描述】:

假设我有这个类:

class Foo:
    def __init__(self):
        self.task1_dict = {}
        self.task2_dict = {}

    def task1(self):
        for i in range(10000000):
            # update self.task1_dict
    
    def task2(self):
        for i in range(10000000):
            # update self.task2_dict

    def run(self):
        self.task1()
        self.task2()

任务 1 和任务 2 都是 CPU 密集型任务并且是非 IO。它们也是独立的,因此您可以假设同时运行它们是线程安全的。

目前,我的班级正在按顺序运行任务,我想对其进行更改,以便任务在多个线程中并行运行。我正在使用 concurrent.future 包中的 ThreadPoolExecutor。

class Foo:
    ...
    def run(self):
        with ThreadPoolExecutor() as executor:
            executor.submit(self.task1)
            executor.submit(self.task2)

问题是当我调用run 方法时,与顺序版本相比,运行时间根本没有减少,甚至略有增加。我猜这是因为 GIL 一次只允许一个线程运行。有什么方法可以并行化这个程序吗?也许是一种克服 GIL 并在 2 个线程上运行 2 个方法的方法?我考虑过切换到ProcessPoolExecutorbut I cannot call the methods since class methods are not picklable。此外,如果我使用多处理,Python 将创建多个Fooself.task1_dict 实例,self.task2_dict 不会相应更新。

【问题讨论】:

    标签: python multithreading concurrency multiprocessing gil


    【解决方案1】:

    您可以按照here的说明使用多处理共享内存

    【讨论】:

      猜你喜欢
      • 2020-06-16
      • 2021-08-15
      • 1970-01-01
      • 2012-09-24
      • 2013-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多