【Python】进程池与线程池

import time, random, os
from concurrent.futures import ProcessPoolExecutor,ThreadPoolExecutor


def task(name):
print('name:%s pid:%s run' % (name, os.getpid()))
time.sleep(random.randint(1,3))


if __name__ == '__main__':
# pool = ProcessPoolExecutor(4) # 限定4个进程
pool = ThreadPoolExecutor(4) # 限定4个线程

for i in range(10): # 同时开10个, 多出来的进程/线程只能阻塞
pool.submit(task, 'caya-%s' % i)

pool.shutdown(wait=True) # 关闭进程池,相当于join 默认 wait=True 所有进程/线程结束池才能关闭

try:
pool.submit(task, 'caya-%s' % 999) # 关闭进程池后不可加入
except RuntimeError as e:
print(e)
print('main')
posted @ 2018-08-26 18:01  caya  阅读(140)  评论(0编辑  收藏  举报