• Python简单的线程池


    class ThreadPool(object):
    
        def __init__(self, max_num=20):
            # 创建一个队列,队列里最多只能有10个数据
            self.queue = queue.Queue(max_num)
            # 在队列里填充线程类
            # 【线程类、线程类、线程类、线程类、线程类、线程类、线程类】
            for i in range(max_num):
                self.queue.put(threading.Thread)
    
        def get_thread(self):
            # 去队列里去数据,
            # queue特性,如果有,对列里那一个出来
            #            如果没有,阻塞,
            return self.queue.get()
    
        def add_thread(self):
            # 往队列里再添加一个线程类
            self.queue.put(threading.Thread)
    
    # pool = ThreadPool(10)
    
    
    pool = ThreadPool(10)
    
    def func(arg, p):
        # 函数内容
        print(arg)
        import time
        time.sleep(2)
    
        # 在线程池里重新添加一个线程(将线程归还给线程池)
        p.add_thread()
    
    for i in range(30):
        # 去线程池里那一个线程,如果有,则池子里拿,如果没有,等直到有人归还线程到线程池
        thread = pool.get_thread()
        # thread = threading.Thread
        t = thread(target=func, args=(i, pool))
        t.start()
    

      

  • 相关阅读:
    【JZOJ5603】【NOI2018模拟3.27】Xjz
    【JZOJ5605】【NOI2018模拟3.26】Arg
    【agc004e】Salvage Robots
    【agc004c】AND Grid
    【agc004d】Teleporter
    【agc002f】Leftmost Ball
    【agc002d】Stamp Rally
    【arc068F】Solitaire
    51nod 1172 Partial Sums V2
    快速数论变换NTT模板
  • 原文地址:https://www.cnblogs.com/alan-babyblog/p/5289865.html
Copyright © 2020-2023  润新知