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