风-fmgao

导航

初探进程池线程池

#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time    : 2018/6/19 10:20
# @File    : 进程池线程池.py

# ProcessPoolExecutor和ThreadPoolExecutor接口一样
# 计算密集型--进程  ,io密集型--线程
# from concurrent.futures import ProcessPoolExecutor,ThreadPoolExecutor
# import os,time,random
#
#
# def task(name):
#     print('name : %s pid: %s run' % (name, os.getpid()))
#     time.sleep(random.randint(1, 3))  # 模拟运行时间
#
#
# if __name__ == '__main__':
#     pool = ProcessPoolExecutor(4)  # 如果不指定,默认就是cpu核数
#     for i in range(10):
#         pool.submit(task, 'egon%s' % i)  # 异步调用,提交完步,不用等,直接运行下面代码
#
#     pool.shutdown()  # 提交任务的入口关闭,默认参数wait=True,没有这句代码先打印主,有最后打印
#
#     print('主')


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


def task():
    print('name : %s pid: %s run' % (currentThread().getName(), os.getpid()))
    time.sleep(random.randint(1, 3))  # 模拟运行时间


if __name__ == '__main__':
    pool = ThreadPoolExecutor(5)  # 如果不指定,默认就是cpu核数
    for i in range(10):
        pool.submit(task, )

    pool.shutdown()

    print('主')


posted on 2018-06-19 11:06  风-fmgao  阅读(81)  评论(0编辑  收藏  举报