MST

星途 面试题库

面试题:Python中concurrent.futures模块常用的类有哪些及简单应用场景

请简述Python的concurrent.futures模块中ThreadPoolExecutor和ProcessPoolExecutor这两个类的主要作用,并且分别给出一个简单示例,说明在哪些场景下会优先选择使用它们。
43.6万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试

ThreadPoolExecutor主要作用

ThreadPoolExecutor用于创建一个线程池,通过线程的方式来异步执行任务。线程适合I/O密集型任务,因为线程间共享内存空间,切换开销相对较小。

ThreadPoolExecutor示例

import concurrent.futures
import time


def io_bound_task():
    time.sleep(2)  # 模拟I/O操作,比如网络请求、文件读取等
    return "I/O bound task completed"


with concurrent.futures.ThreadPoolExecutor() as executor:
    future = executor.submit(io_bound_task)
    print(future.result())

在网络爬虫、文件读写等I/O密集型场景下优先选择ThreadPoolExecutor, 线程切换开销小,能有效利用I/O等待时间。

ProcessPoolExecutor主要作用

ProcessPoolExecutor用于创建一个进程池,以进程的方式异步执行任务。进程适合CPU密集型任务,每个进程有独立的内存空间,能充分利用多核CPU。

ProcessPoolExecutor示例

import concurrent.futures
import time


def cpu_bound_task():
    result = 0
    for i in range(100000000):
        result += i
    return result


with concurrent.futures.ProcessPoolExecutor() as executor:
    future = executor.submit(cpu_bound_task)
    print(future.result())

在数据处理、科学计算等CPU密集型场景下优先选择ProcessPoolExecutor,可以充分利用多核CPU资源,提升计算速度。