Python Multithreaded Application Introduction

Source: Internet
Author: User
Python makes it easy to support multithreading. You can quickly create threads, mutexes, semaphores, and so on, enabling threads to read and write synchronous mutexes. In the ointment, Python runs on a python virtual machine, creating multithreading that could be virtual threads that need to be polled by a Python virtual machine for scheduling, which greatly reduces the availability of Python multi-threading. We use the classic producer and consumer questions today to illustrate Python's multithreaded use of code:

Copy CodeThe code is as follows:


#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 (20):
Print self.getname (), ' adding ', I, ' to queue '
Self.sharedata.put (i)
Time.sleep (Random.randrange (10)/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 (20):
Print self.getname (), ' Got a value: ', Self.sharedata.get ()
Time.sleep (Random.randrange (10)/10.0)
Print self.getname (), ' finished '


# Main Thread

def main ():

Queue = Queue ()
Producer = producer (' producer ', queue)
consumer = consumer (' Consumer ', queue)
print ' Starting threads ... '
Producer.start ()
Consumer.start ()
Producer.join ()
Consumer.join ()
print ' All threads has terminated. '
if __name__ = = ' __main__ ':
Main ()


You can run this code yourself, and you may have a different feeling! Understand that you could use Python cookielib again to result in Python urllib writing a multithreaded download page script should be fine
  • 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.