Python does not provide the thread pool functionality by default, so if you want to use a thread pool, you need to use a third-party module or custom thread
The more threads are not the better, the context switch of the thread affects the performance of the server
Thread pool: A container that has the maximum number, takes one less, waits on a wireless path, executes the thread, and returns the thread
__author__='Alex'#Coding:utf-8ImportQueueImportThreadingImport TimeclassThreadPool:def __init__(self,maxsize=5): Self.maxsize=maxsize self._q=queue. Queue () forIinchRange (5): Self._q.put (Threading. Thread)defGet_thread (self):returnSelf._q.get ()defAdd_thread (self): Self._q.put (Threading. Thread) Pool= ThreadPool (5)defTask (args,p):Print(args) time.sleep (2) P.add_thread () forIinchRange (100): T=pool.get_thread () obj= T (Target=task,args =(I,pool)) Obj.start ()
This simple program realizes the basic function of thread pool, can only have 5 threads at a time, but also has a great limitation, 1, the thread can not be recycled, 5 threads are generated each time, but the line Cheng cannot be retracted (garbage collection mechanism is recycled), after every 5 threads end, just regenerate new thread; 2, If the number of threads required range (100) is less than the value of the created pool that we define (5), then it is wasted, there is no need to initially create 5 threads (the thread pool opens to the maximum at one time).
Python thread Pool