Detailed description of the Python Thread Pool

Source: Internet
Author: User

The following is a summary of my experiences with the Python thread pool. for users who have never been familiar with programming languages or have a few programming languages, the Python language is definitely one of the best choices, it is recommended that beginners learn programming from Python first.

 
 
  1. import Queue, threading, sys   
  2. from threading import Thread   
  3. import time,urllib   
  4. # working thread   
  5. class Worker(Thread):   
  6.    worker_count = 0   
  7.    def __init__( self, workQueue, resultQueue, timeout = 0, **kwds):   
  8.        Thread.__init__( self, **kwds )   
  9.        self.id = Worker.worker_count   
  10.        Worker.worker_count += 1   
  11.        self.setDaemon( True )   
  12.        self.workQueue = workQueue   
  13.        self.resultQueue = resultQueue   
  14.        self.timeout = timeout   
  15.        self.start( )   
  16.    def run( self ):   
  17.        ''' the get-some-work, do-some-work main loop of worker threads '''   
  18.        while True:   
  19.            try:   
  20.                callable, args, kwds = self.workQueue.get(timeout=self.timeout)   
  21.                res = callable(*args, **kwds)   
  22.                print "worker[%2d]: %s" % (self.id, str(res) )   
  23.                self.resultQueue.put( res )   
  24.            except Queue.Empty:   
  25.                break   
  26.            except :   
  27.                print 'worker[%2d]' % self.id, sys.exc_info()[:2]   
  28.                   
  29. class WorkerManager:   
  30.    def __init__( self, num_of_workers=10, timeout = 1):   
  31.        self.workQueue = Queue.Queue()   
  32.        self.resultQueue = Queue.Queue()   
  33.        self.workers = []   
  34.        self.timeout = timeout   
  35.        self._recruitThreads( num_of_workers )   
  36.    def _recruitThreads( self, num_of_workers ):   
  37.        for i in range( num_of_workers ):   
  38.            worker = Worker( self.workQueue, self.resultQueue, self.timeout )   
  39.            self.workers.append(worker)   
  40.    def wait_for_complete( self):   
  41.        # ...then, wait for each of them to terminate:   
  42.        while len(self.workers):   
  43.            worker = self.workers.pop()   
  44.            worker.join( )   
  45.            if worker.isAlive() and not self.workQueue.empty():   
  46.                self.workers.append( worker )   
  47.        print "All jobs are are completed."   
  48.    def add_job( self, callable, *args, **kwds ):   
  49.        self.workQueue.put( (callable, args, kwds) )   
  50.    def get_result( self, *args, **kwds ):   
  51.        return self.resultQueue.get( *args, **kwds )  

The Worker class is a Python thread pool that constantly obtains the tasks to be executed from the workQueue queue, executes the tasks, and writes the results to the resultQueue. WorkQueue and resultQueue are both ready-made and secure, and their internal operations on each thread are mutually exclusive. When the task retrieved from workQueue times out, the thread ends.

WorkerManager initializes the Python thread pool, provides interfaces for adding tasks to the queue and obtaining results, and waits until all tasks are completed. A typical test example is as follows. It uses 10 threads to download the content of a fixed page. Different tasks should be executed in actual applications.

 
 
  1. def test_job(id, sleep = 0.001 ):   
  2.    try:   
  3.        urllib.urlopen('[url]https://www.gmail.com/[/url]').read()   
  4.    except:   
  5.        print '[%4d]' % id, sys.exc_info()[:2]   
  6.    return id   
  7. def test():   
  8.    import socket   
  9.    socket.setdefaulttimeout(10)   
  10.    print 'start testing'   
  11.    wm = WorkerManager(10)   
  12.    for i in range(500):   
  13.        wm.add_job( test_job, i, i*0.001 )   
  14.    wm.wait_for_complete()   
  15.    print 'end testing'  
  1. Introduction to Python system files
  2. How to correctly use Python Functions
  3. Detailed introduction and analysis of Python build tools
  4. Advantages of Python in PythonAndroid
  5. How to Use the Python module to parse the configuration file?

Related Article

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.