concurrent.futures模块提供了高度封装的异步调用接口 ThreadPoolExecutor:线程池,提供异步调用 ProcessPoolExecutor: 进程池,提供异步调用 Both implement the same interface, which is defined by the abstract Executor class.
The ProcessPoolExecutor class is an Executor subclass that uses a pool of processes to execute calls asynchronously. ProcessPoolExecutor uses the multiprocessing module, which allows it to side-step the Global Interpreter Lock but also means that only picklable objects can be executed and returned.
class concurrent.futures.ProcessPoolExecutor(max_workers=None, mp_context=None) An Executor subclass that executes calls asynchronously using a pool of at most max_workers processes. If max_workers is None or not given, it will default to the number of processors on the machine. If max_workers is lower or equal to 0, then a ValueError will be raised.
if __name__ == '__main__': # 设置开启进程的最大数量 executor=ProcessPoolExecutor(max_workers=3)
futures=[] # 虽然循环里会开10个进程,但是进程池里最多3 其他的进程就会等着——从始至终池子里最多有三个进程 for i in range(10): # 异步提交任务(只触发任务开启,不等待结果) future=executor.submit(task,i) futures.append(future) # 主进程等待所有子进程的任务都完毕在结束——join操作 # 这时要设置 shutdown(True) or shutdown(wait=True) executor.shutdown(True) print('+++>') for future in futures: print(future.result())
线程池
介绍
1 2 3 4 5 6 7
ThreadPoolExecutor is an Executor subclass that uses a pool of threads to execute calls asynchronously. class concurrent.futures.ThreadPoolExecutor(max_workers=None, thread_name_prefix='') An Executor subclass that uses a pool of at most max_workers threads to execute calls asynchronously.
Changed in version 3.5: If max_workers is None or not given, it will default to the number of processors on the machine, multiplied by 5, assuming that ThreadPoolExecutor is often used to overlap I/O instead of CPU work and the number of workers should be higher than the number of workers for ProcessPoolExecutor.
New in version 3.6: The thread_name_prefix argument was added to allow users to control the threading.Thread names for worker threads created by the pool for easier debugging.
用法
1
把ProcessPoolExecutor换成ThreadPoolExecutor,其余用法全部相同
map方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor