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()

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

 

posted @ 2017-10-31 10:11  任飞儿  阅读(182)  评论(0编辑  收藏  举报