table of Contents
Thread pool and process pool
Pool: represents a container. Thread pool is a thread storage containers, storage containers process pool is the process of
Why should the thread pool to store, process pool
- Avoid frequent creation and destruction (processes, threads) to resource overhead
- Can limit the number of threads exist to ensure that the server will not collapse because of a lack of resources
- Help us manage the creation and destruction of threads
- Manage the distribution of tasks
Process pool:
# 进程池
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
Thread Pool:
# 线程池
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
If the primary process does not end, pond inside the process or thread, also has been surviving