MST
星途 面试题库

面试题:Python中ThreadPoolExecutor线程管理的基础应用

请简述在Python中使用ThreadPoolExecutor创建线程池并提交任务的基本步骤,同时说明如何获取任务的执行结果。
14.4万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
  1. 导入模块
    from concurrent.futures import ThreadPoolExecutor
    
  2. 创建线程池
    executor = ThreadPoolExecutor(max_workers=5)  # max_workers指定线程池中线程的最大数量
    
  3. 定义任务函数
    def task_function(x):
        return x * x
    
  4. 提交任务到线程池
    future = executor.submit(task_function, 3)  # 提交任务,3为任务函数的参数
    
  5. 获取任务执行结果
    result = future.result()  # 获取任务执行的结果,如果任务未完成,会阻塞等待直到任务完成
    print(result)  # 输出9
    
  6. 关闭线程池
    executor.shutdown()  # 不再接受新任务,等待所有已提交任务完成
    

也可以使用with语句来自动管理线程池的生命周期:

with ThreadPoolExecutor(max_workers=5) as executor:
    future = executor.submit(task_function, 3)
    result = future.result()
    print(result)

这样在with块结束时,线程池会自动关闭。