Python Multithreaded Application Introduction _python

Source: Internet
Author: User
Tags sleep thread class

Python can easily support multithreading. You can quickly create elements such as threads, mutexes, semaphores, and so on that support thread read-write synchronization mutexes. The drawback is that Python is running on a Python virtual machine, creating multithreading that might be virtual threads that need to be polled by Python virtual machines, which greatly reduces the availability of Python threads. We have today used the classic producer and consumer issues to illustrate the use of Python multithreading code:

#encoding =utf-8 Import Threading Import random import time from queue Import Queue class Producer (threading. Thread): Def __init__ (self, ThreadName, queue): Threading. Thread.__init__ (self, name = threadname) self.sharedata = Queue def run (self): For I in range: print Self.getname (), ' adding ', I, ' to queue ' self.sharedata.put (i) Time.sleep (Random.randrange ()/10.0) print self.getname (), ' Finished ' # Consumer thread class Consumer (threading. Thread): Def __init__ (self, ThreadName, queue): Threading. Thread.__init__ (self, name = threadname) self.sharedata = Queue def run (self): For I in range: print Self.getna  Me (), ' Got a value: ', Self.sharedata.get () Time.sleep (Random.randrange ()/10.0) print self.getname (), ' finished ' # Main Thread def main (): queue = Queue () producer = producer (' producer ', queue) consumer = consumer (' Consumer ', queue) p Rint ' Starting threads ... ' Producer.start () Consumer.start () Producer.join () consumer.join () print 'All threads have terminated. ' 
 if __name__ = = ' __main__ ': Main ()

You run this code yourself, you may have a different feeling! Understanding later can use Python cookielib again results python urllib write a multithreaded download Web page script should be no problem

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.