zoukankan      html  css  js  c++  java
  • python low版线程池

    1.low版线程池
    设计思路:运用队列queue

    线程类名放入队列中,执行一个就拿一个出来
    import queue
    import threading


    class ThreadPool(object):

    def __init__(self, max_num=20):
    self.queue = queue.Queue(max_num) #创建队列,最大数为20
    for i in range(max_num):
    self.queue.put(threading.Thread) #将类名放入队列中

    def get_thread(self):
    return self.queue.get() #从队列中取出类名

    def add_thread(self):
    self.queue.put(threading.Thread) #进类名放入队列中

    def func(arg, p): #定义一个函数
    print(arg)
    import time
    time.sleep(2)
    p.add_thread()


    pool = ThreadPool(10) #创建对象,并执行该类的构造方法,即将线程的类名放入队列中

    for i in range(30):
    thread = pool.get_thread() #调用该对象的get_thread方法,取出类名
    t = thread(target=func, args=(i, pool)) #创建对象,执行func,参数在args中
    t.start()

    由于此方法要求使用者修改原函数,并在原函数里传参数,且调用方法也发生了改变,并且有空闲线程浪费资源,实际操作中并不方便,故设计了下一版线程池。

  • 相关阅读:
    【转载】关于C#中动态加载AppDomain的问题
    poj2239
    poj2231
    poj2229
    poj2234
    poj2236
    前 路
    只含一个单词的句子
    做人准则
    改变人生的32句励志名言
  • 原文地址:https://www.cnblogs.com/mmbbflyer/p/7760209.html
Copyright © 2011-2022 走看看