zoukankan      html  css  js  c++  java
  • 使用池

    什么是池?

    • 在程序开始时, 还没有提交任务,先创建几个线程或进程, 并放在一个池子里, 这就是池.

    为什么要用池?

    • 先开好线程/进程, 等有任务之后就可以直接使用这个池中的数据

    • 开好的线程/进程会一直存在于这个池中, 可以被多个任务反复利用, 从而能够减少开启 关闭 调度线程/进程的时间开销

    • 池中线程/进程的个数控制操作系统需要调度任务的个数, 控制池中的单位, 这样有利于提高提高操作系统的效率, 减轻操作系统的负担

    python中相关模块的发展过程

    • threading模块, 没有提供池
    • multiprocessing模块, 仿照threading模块写的, 但是提供了Pool
    • concurrent.futures模块, 提供了线程池ThreadPoolExecutor和进程池ProcessPoolExecutor, 并且能够用相似的方式开始和使用

    代码示例

    from concurrent.futures import ThreadPoolExecutor
    from threading import current_thread
    import time
    
    
    def func(n):
        print(n, current_thread().ident, 'start')
        time.sleep(1)
        print(n, current_thread().ident, 'end')
        return n*n
    
    
    def print_fun(res):
        print(res.result())
    
    
    if __name__ == '__main__':
        # 创建线程池
        tp = ThreadPoolExecutor(4)
    
        for i in range(20):                     # 异步非阻塞
            # 提交任务到线程池
            ret = tp.submit(func, i)            # Future未来对象
    
            # 回调函数, 异步阻塞, 给ret对象绑定一个回调函数, 等待ret对应的任务完成之后立即调用print_fun函数
            # 实现对结果的立即处理, 不用按照顺序接受处理
            ret.add_done_callback(print_fun)
    
  • 相关阅读:
    [OpenWRT]判断WDS是否开启
    【cocos2d-js官方文档】一、搭建 Cocos2d-JS 开发环境
    noi Big String 超级字符串
    序列 xulie (2017青岛)
    %%%城市交通费 city //程序超时
    3.密码pasuwado————记第一次超越Candy?
    图论-欧拉回路(邻接链表)
    blue and red ball
    魔方→︿←
    The first DP!
  • 原文地址:https://www.cnblogs.com/KX-Lau/p/13576775.html
Copyright © 2011-2022 走看看