Python: concurrent.futures

 

 

 

 

 

 

 

 

import datetime, multiprocessing, logging, time, threading
from concurrent import futures

FORMAT = '%(asctime)-9s [%(processName)-10s %(process)6d] %(lineno)-3s [%(threadName)-11s %(thread)6d] %(message)s'
logging.basicConfig(format=FORMAT, level=logging.DEBUG,datefmt='%H:%M:%S')


def vacuity(n):
    logging.info(f'commence: n = {n}')
    time.sleep(4)
    logging.info(f'closure;  n = {n}')


# 创建线程池, 容量: 3
executor = futures.ThreadPoolExecutor(max_workers=3, thread_name_prefix='prefix')

futures = []

for b in range(3):
    future = executor.submit(vacuity, b)  # 返回Future对象, 提交工作
    futures.append(future)

for b in range(3, 6):
    future = executor.submit(vacuity, b)
    futures.append(future)

while True:
    time.sleep(2)
    logging.info(threading.enumerate())
    flag = True
    for future in futures:
        logging.error(future.done())
        flag = flag and future.done()
    if flag:
        executor.shutdown()  # 不用频繁清理池
        logging.critical(threading.enumerate())
        break

 

import datetime, multiprocessing, logging, time, threading
from concurrent import futures

FORMAT = '%(asctime)-9s [%(processName)-10s %(process)6d] %(lineno)-3s [%(threadName)-11s %(thread)6d] %(message)s'
logging.basicConfig(format=FORMAT, level=logging.DEBUG, datefmt='%H:%M:%S')


def vacuity(n):
    logging.info(f'commence: n = {n}')
    time.sleep(4)
    logging.info(f'closure;  n = {n}')


if __name__ == '__main__':
    # 创建线程池, 容量: 3
    executor = futures.ProcessPoolExecutor(max_workers=3)

    futures = []

    for b in range(3):
        future = executor.submit(vacuity, b)  # 返回Future对象, 提交工作
        futures.append(future)

    for b in range(3, 6):
        future = executor.submit(vacuity, b)
        futures.append(future)

    while True:
        time.sleep(2)
        logging.info(threading.enumerate())
        flag = True
        for future in futures:
            logging.error(future.done())
            flag = flag and future.done()
        if flag:
            executor.shutdown()  # 不用频繁清理池
            logging.critical(threading.enumerate())
            break

 

 

 

posted @ 2022-02-25 23:52  ascertain  阅读(48)  评论(0编辑  收藏  举报