zoukankan      html  css  js  c++  java
  • (11)线程池(最新的concurrent.futures包去开启)

    '''concurrent.futures是最新的开启线程池的包'''
    import time
    from concurrent.futures import ThreadPoolExecutor #开启线程池导入的模块

    def task(i):
    print(i)
    time.sleep(1)
    return i

    if __name__ == '__main__':
    '''线程池的个数是cpu数 * 5,不传参默认就是cpu数 * 5'''
    t = ThreadPoolExecutor(20) #在池里开了20个线程
    res_l = []
    for i in range(30):
    '''线程池可以读取返回值的结果,但是需要将返回值放入变量并且存入列表用for循环读取'''
    res = t.submit(task,i) # 就是等于start的功能
    res_l.append(res) # 将返回值放入列表
    t.shutdown() #合并了进程池中close和join的工作,停止提交任务并等待子线程执行完毕
    for res in res_l:
    print(res.result()) #要读取返回值就要用result方法


    '''concurrent.futures是最新的开启线程池的包'''
    import time
    from concurrent.futures import ProcessPoolExecutor #开启进程池


    def task(i):
    # print(i)
    time.sleep(1)
    return i

    if __name__ == '__main__':
    t = ProcessPoolExecutor(5) #在池里开了5个进程
    res_l = []
    for i in range(30):
    '''进程池可以读取返回值的结果,但是需要将返回值放入变量并且存入列表用for循环读取'''
    res = t.submit(task,i) # 就是等于start的功能
    res_l.append(res) # 将返回值放入列表
    t.shutdown() #合并了进程池中close和join的工作,停止提交任务并等待子线程执行完毕
    for res in res_l:
    print(res.result()) #要读取返回值就要用result方法
     
  • 相关阅读:
    c语言中重要函数
    python 类属性、对象属性
    windows下PIP安装模块编码错误解决
    python爬取百思不得姐视频
    ubuntu下刷新dns
    pycharm设置安装python第三方插件
    python将str转换成字典
    pyqt加载图片
    Python端口扫描器
    自己构造用于异步请求的JSON数据
  • 原文地址:https://www.cnblogs.com/shizhengquan/p/10271677.html
Copyright © 2011-2022 走看看