自定义简单版本python线程池

python未提供线程池模块,在python3上用threading和queue模块自定义简单线程池,代码如下:

 1 #用threading queue 做线程池
 2 import queue
 3 import threading
 4 class ThreadPool():
 5     def __init__(self,arg):#创建队列,在队列每个位置放一个threading.Tread类
 6         self.queue_obj = queue.Queue(arg)
 7         for i in range(arg):
 8             self.queue_obj.put(threading.Thread)
 9     def thread_get(self):#执行这个方法后把得到的类threading.Tread返回
10         return self.queue_obj.get()
11     def thread_add(self):#把threading.Tread类放到队列
12         self.queue_obj.put(threading.Thread)
13 def func(b,a):
14     b.thread_add() #用函数执行ThreadPool类里的thread_add方法
15     print(a)
16 
17 threading_pool = ThreadPool(5) #创建队列为5的线程池,每个位置放一个threading.Thread
18 thread = threading_pool.thread_get() #threading.Thread
19 thread_obj = thread(target=func,args=(threading_pool,11,)) #创建线程,把threading_pool和11传给func函数,达到用线程处理数据并且把threading.Thread类放到队列
20 thread_obj.start()#执行线程
自定义简单线程池
原文地址:https://www.cnblogs.com/wenxianfeng/p/9985856.html