Python的进程池和线程池
线程池
- 都在一个进程内 GIL 不适合密集型计算
- 共享进程资源,存在不安全的线程
from concurrent.futures import ThreadPoolExecutor
def task(n):
return n * 2
if __name__ == '__main__':
with ThreadPoolExecutor(max_workers=4) as executor:
results = list(executor.map(task, range(10)))
print(results)
进程池
- 相互隔离 资源开销较大
- 可以避开 GIL
- 进程通讯比较麻烦,线程安全
from concurrent.futures import ProcessPoolExecutor
def task(n):
return n * 2
if __name__ == '__main__':
with ProcessPoolExecutor(max_workers=4) as executor:
results = list(executor.map(task, range(10)))
print(results)
本文来自博客园,作者:vx_guanchaoguo0,转载请注明原文链接:https://www.cnblogs.com/guanchaoguo/p/18409527