Why use 'pool':
The pool is used to limit the number of concurrent tasks, and limit our computer to perform tasks concurrently within a range that we can afford.
When to install processes in the pool: Concurrent tasks are computationally intensive.
When to install threads in the pool: Concurrent tasks are I/O intensive.
Use of the process pool
from concurrent.futures import ProcessPoolExecuto import time,os,random def task(x): print('%s goes to service' %os.getpid()) time.sleep (random.randint (4,5)) return x**2 if __name__ == '__main__': p=ProcessPoolExecutor(max_workers=5)#The number of processes opened by default is the number of cpu cores for i in range(20): p.submit(task,i)operation result:
Use of thread pool:
from concurrent.futures import ThreadPoolExecutor import time,os,random def task(x): print('%s goes to service' %os.getpid()) time.sleep (random.randint (4,5)) return x**2 if __name__ == '__main__': p=ThreadPoolExecutor()#The number of processes opened by default is the number of cpu cores for i in range(20): p.submit(task,i)
operation result: