并发编程之线程池进程池
线程池与进程池
池:表示容器。线程池就是存放线程的容器,进程池就是存放进程的容器
为什么要存放到线程池、进程池中
- 避免频繁的创建和销毁(进程、线程)来的资源开销
- 可以限制同时存在的线程数量,以保证服务器不会因为资源不足而崩溃
- 帮我们管理了线程的创建和销毁
- 管理了任务的分配
进程池:
# 进程池
from concurrent.futures import ProcessPoolExecutor
from multiprocessing import Process
import os
import time
def task():
time.sleep(0.1)
print(os.getpid())
if __name__ == '__main__':
pool = ProcessPoolExecutor(3)
# 提交任务到池子中
pool.submit(task)
# time.sleep(1)
pool.submit(task)
147332
147320
线程池:
# 线程池
from concurrent.futures import ThreadPoolExecutor
from threading import active_count,enumerate,currentThread
import os
import time
def task():
print(currentThread().name)
# 创建线程池
pool = ThreadPoolExecutor(3)
# 提交任务到池子中
pool.submit(task)
pool.submit(task)
print(f"{enumerate()}")
print(f"{active_count()}")
ThreadPoolExecutor-0_0
ThreadPoolExecutor-0_0
[<_MainThread(MainThread, started 135020)>, <Thread(ThreadPoolExecutor-0_0, started daemon 134904)>, <Thread(ThreadPoolExecutor-0_1, started daemon 134872)>]
3
如果主进程不结束,池子里面的进程或线程,也是一直存活的