利用threading模块和queue模块在python3解释器上创建一个简单的python线程池

python解释器没提供线程池模块,故在python3上自定义python线程池简单版本,代码如下

#用threading queue 做线程池

import queue
import threading
class ThreadPool():
def __init__(self,arg):#创建队列,在队列每个位置放一个threading.Tread类
self.queue_obj = queue.Queue(arg)
for i in range(arg):
self.queue_obj.put(threading.Thread)
def thread_get(self):#执行这个方法后把得到的类threading.Tread返回
return self.queue_obj.get()
def thread_add(self):#把threading.Tread类放到队列
self.queue_obj.put(threading.Thread)
def func(b,a):
b.thread_add() #用函数执行ThreadPool类里的thread_add方法
print(a)

threading_pool = ThreadPool(5) #创建队列为5的线程池,每个位置放一个threading.Thread
thread = threading_pool.thread_get() #threading.Thread
thread_obj = thread(target=func,args=(threading_pool,11,)) #创建线程,把threading_pool和11传给func函数,达到用线程处理数据并且把threading.Thread类放到队列
thread_obj.start()#执行线程

猜你喜欢

转载自www.cnblogs.com/wenxianfeng/p/9985149.html