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)

posted @ 2024-09-12 09:21  vx_guanchaoguo0  阅读(5)  评论(0编辑  收藏  举报