from multiprocessing import Pool
import os
def task(n):
"""简单的任务函数,返回输入的平方和进程ID"""
return n * n, os.getpid()
if __name__ == '__main__':
# 创建一个包含4个进程的进程池
with Pool(processes=4) as pool:
# 使用map方法将task函数应用到一个列表上
results = pool.map(task, range(10))
# 打印结果
for result in results:
print(f"Result: {result[0]}, Process ID: {result[1]}")
multiprocessing
模块中导入Pool
类。task
函数接受一个参数n
,返回其平方值以及执行该任务的进程ID。with Pool(processes=4) as pool
创建一个包含4个进程的进程池。with
语句确保进程池在使用完毕后正确关闭。pool.map
方法将task
函数应用到range(10)
生成的序列上。map
方法会将序列中的每个元素传递给task
函数,并在进程池中的不同进程中并行执行。results
列表,打印每个任务的结果及其对应的进程ID。这个示例展示了如何使用Python的multiprocessing.Pool
来并行执行任务,并获取每个任务的执行结果和执行它的进程ID。
上一篇:python读取ini配置文件
下一篇:查python版本
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站