Python thread Pool

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.