Python标准库为我们提供了threading和multiprocessing模块编写相应的多线程/多进程代码,但是当项目达到一定的规模,频繁创建/销毁进程或者线程是非常消耗资源的,这个时候我们就要编写自己的线程池/进程池,以空间换时间。但从Python3.2开始,标准库为我们提供了concurrent.futures模块,它提供了ThreadPoolExecutor和ProcessPoolExecutor两个类,实现了对threading和multiprocessing的进一步抽象,对编写线程池/进程池提供了直接的支持。
 
模块:concurrent.futures模块的ThreadPoolExecutor,ProcessPoolExecutor子类
 
简单实例:
from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor
import time

def task(arg1,arg2):
    print(arg1,arg2)
    time.sleep(1)

# pool = ProcessPoolExecutor(10)
pool = ThreadPoolExecutor(10)

for i in range(100):
    pool.submit(task,i,i)

  

 

 

相关文章:

  • 2021-07-03
  • 2021-11-14
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-01
猜你喜欢
  • 2022-02-14
  • 2021-11-23
  • 2022-12-23
  • 2021-11-02
  • 2022-12-23
  • 2022-01-23
  • 2019-09-21
相关资源
相似解决方案