技术文章和资源

技术文章(时间排序)

热门类别

Python PHP MySQL JDBC Linux

Python 中的 ProcessPoolExecutor 类

pythonserver side programmingprogramming

Python 中的 ProcessPoolExecutor 类是 concurrent.futures 模块的一部分,是使用进程和线程异步执行函数的高级接口。ProcessPoolExecutor 允许我们使用多个进程并行执行多个函数,这对于受益于并行化进程的 CPU 密集型任务特别有用。

多处理和多线程

在了解 ProcessPoolExecutor 类之前,我们必须了解多处理和多线程。多处理和多线程是用于实现并行进程的技术,它们在管理和创建并发任务的方式上有所不同。

多处理使用多个进程并行执行任务,每个进程都有自己的内存空间,以避免共享内存和并发问题。它也是进程之间的一种通信方式,可能更复杂、更昂贵,因为必须在进程之间序列化和反序列化数据。多处理特别用于 CPU 密集型任务,有利于执行并行化任务,如数值计算或图像处理等。在 Python 中,我们有一个模块多处理,它允许我们创建和管理进程,而池类用于管理工作进程池以并行执行函数。

多线程在单个进程中使用多个线程来实现并行性,每个线程与主线程共享相同的内存空间,这可以简化线程之间的通信。这意味着我们在访问共享数据时需要小心,以避免并发问题,如竞争条件或死锁。多线程用于执行 I/O 密集型任务,这些任务有利于并行化,如网络编程或文件处理等。在 Python 中,我们有模块线程来创建和管理线程,以及线程类,用于创建新线程并在该线程中执行函数。锁类用于同步线程之间共享数据的访问。

创建 ProcessPoolExecutor

创建 ProcessPoolExecutor 的过程与 ThreadPoolExecutor 类似,唯一的区别是我们必须从 parallel.futures 模块导入该类。我们将使用 OS 模块获取我们在池中执行的当前任务 PID。

示例

from concurrent.futures import ProcessPoolExecutor
import os
def task():
   print("Current executing task PID {}".format(os.getpid()))
if __name__ == '__main__':
   result =[]
   with ProcessPoolExecutor(max_workers=3) as exe:
      result1 = exe.submit(task())

输出

Current executing task PID 6652

示例

from concurrent.futures import ProcessPoolExecutor
import os
values = [10,40,30,4]
def square(x):
   print(f'square of {x}:{x*x}')
   print("Current executing task PID {}".format(os.getpid()))
if __name__ == '__main__':
   result =[]
   with ProcessPoolExecutor(max_workers = 5) as exe:
      for i in values:
         result = exe.submit(square(i))

输出

square of 10:100
Current executing task PID 19276
square of 40:1600
Current executing task PID 19276
square of 30:900
Current executing task PID 19276
square of 4:16
Current executing task PID 19276

相关文章