Python:CPU 多线程密集型任务
Python: CPU intensive tasks on multiple threads
假设我有这个 class:
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。它们也是独立的,因此您可以假设 运行 同时使用它们是线程安全的。
目前,我的 class 是按顺序 运行 执行任务,我想更改它,以便任务 运行 在多个线程中并行执行。我正在使用 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 个方法的方法?我考虑过改用ProcessPoolExecutor
、but I cannot call the methods since class methods are not picklable。此外,如果我使用多处理,Python 将创建 Foo
和 self.task1_dict
的多个实例,并且 self.task2_dict
不会相应更新。
您可以使用多处理共享内存,如here
所述
假设我有这个 class:
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。它们也是独立的,因此您可以假设 运行 同时使用它们是线程安全的。
目前,我的 class 是按顺序 运行 执行任务,我想更改它,以便任务 运行 在多个线程中并行执行。我正在使用 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 个方法的方法?我考虑过改用ProcessPoolExecutor
、but I cannot call the methods since class methods are not picklable。此外,如果我使用多处理,Python 将创建 Foo
和 self.task1_dict
的多个实例,并且 self.task2_dict
不会相应更新。
您可以使用多处理共享内存,如here
所述