简版线程池

 1 import queue
 2 import threading
 3 
 4 
 5 class ThreadPool(object):
 6 
 7     def __init__(self, max_num=20):
 8         self.queue = queue.Queue(max_num)
 9         for i in range(max_num):
10             self.queue.put(threading.Thread)
11 
12     def get_thread(self):
13         return self.queue.get()
14 
15     def add_thread(self):
16         self.queue.put(threading.Thread)
17 
18 pool = ThreadPool(10)
19 def func(arg, p):
20     print(arg)
21     import time
22     time.sleep(2)
23     p.add_thread()
24 
25 
26 for i in range(30):
27     thread = pool.get_thread()
28     t = thread(target=func, args=(i, pool))
29     t.start()

 

posted @ 2017-02-25 20:35  失落的黎明  阅读(102)  评论(0编辑  收藏  举报