Key points analysis of thread pool
1. Consider establishing the number of threads
2. The status of the thread pool
With open (' flog ') as F:
F.write ()
3. Close the thread
Instance (simple instance)
Principle:
1: Create 10 thread objects
2:queue the queue to fetch the thread. Available: take; otherwise: wait
3: Thread execution is complete and returned to the thread pool
#!/usr/bin/env python# coding:utf-8import queueimport Threading "" "1: Create 10 thread objects 2:queue queue fetch thread. Available: take; otherwise: Wait 3: Thread execution complete, return to thread Pool "" "Class ThreadPool (object): # Set a default parameter Max_num def __init__ (self,max_num=20): # Create a queue Self.queue = Queue.queue (max_num) # Loop Create 1 objects for i in Xrange (max_num): self.queue.put ( Threading. Thread) def get_thread (self): return Self.queue.get () # Use the class def add_thread (self): Self.queue.put (Threading. Thread) # Create object # create 1 queue with up to 10 threads pool = ThreadPool (+) def func (arg,p): print arg import time time.sleep ( 2) P.add_thread () # 300 tasks to execute for i in xrange: # Gets a thread, thread = Pool.get_thread () # executes this thread t = Thread (target=func,args= (i,pool)) T.start ()
Example (Twisted.python.threadpool)
#!/usr/bin/env python# coding:utf-8import contextlibdoing = [] @contextlib. Contextmanagerdef Show (Li,item): # print "Before" doing.append (item) yield doing.remove (item) print Len (doing) with show (doing,1): print ' with ' print len (doing) print Len (doing)
Key points analysis of thread pool