day32-2 process thread pool and pool

Process and thread pool pool

Thread pool is a thread pool equipment, pool process pool is loaded process.

1. avoid frequent creating and destroying threads (process) to bring resource overhead

2. You can limit the number of threads that exist to ensure that the server does not lead to collapse because the resource

3. You can help us manage the life cycle of the thread

4. Management tasks assigned

Use the thread pool

import time
from concurrent.futures import ThreadPoolExecutor
from threading import currentThread


def task():
    time.sleep(2)
    print(currentThread().name)  # 打印线程名


pool = ThreadPoolExecutor(5)  # 创建线程池,指定最多可以容纳5个线程
for i in range(10):
    pool.submit(task)  # 提交任务到池子中


print('start...')
pool.submit(task)  # 线程池中的线程执行完后会一直存活
pool.shutdown()  # 存活直到强制关闭线程池
pool.submit(task)  # 关闭后再次提交会报错 

Use of process pool

import os
import time
from concurrent.futures import ProcessPoolExecutor


def task():
    time.sleep(2)
    print("current pid:", os.getpid())


if __name__ == '__main__':
    pool = ProcessPoolExecutor(3)  # 创建进程池,指定最大可以容纳3个进程
    for i in range(10):
        pool.submit(task)  # 提交任务到进程池中

    pool.shutdown()  # 存活直到强制关闭进程池
    pool.submit(task)  # 关闭后再次提交会报错 

submit (task, parameters) when the # pass parameters to give the task, do not write args, direct write parameters like

Guess you like

Origin www.cnblogs.com/863652104kai/p/11146147.html