RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:8:30-17:00
你可能遇到了下面的问题
关闭右侧工具栏

新闻中心

这里有您想知道的互联网营销解决方案
concurrent模块

ThreadPoolExecutor代码笔记

import threading
from concurrent import futures
import logging
import time

FORMAT = '%(processName)s %(threadName)s %(process)d %(thread)d %(message)s'
logging.basicConfig(level=logging.INFO, format=FORMAT)

def worker(n):
    logging.info('begin to work{}'.format(n))
    time.sleep(5)
    logging.info('finished {}'.format(n))

executor = futures.ThreadPoolExecutor(max_workers=3)
fs = []
for i in range(3):
    future = executor.submit(worker, i)
    fs.append(future)

for i in range(3, 6):
    future = executor.submit(worker, i)
    fs.append(future)

while True:
    time.sleep(2)
    logging.info(threading.enumerate())

    flag = True
    for f in fs:
        logging.info(f.done)
        flag = flag and f.done()

    if flag:
        executor.shutdown()   # 清理池
        logging.info(threading.enumerate())
        break

# 如果想改成进程,只需要将 ThreadPoolExecutor 改成 ProcessPoolExecutor
# 但是注意,一定要写在 __name__ == '__main__' 代码块下

当前题目:concurrent模块
本文网址:http://cqwzjz.cn/article/pijesd.html