Python supports multiple threads. Allows you to quickly create threads, mutex locks, semaphores, and other elements, and supports synchronization and mutex between read and write threads. In the US, Python runs on a python virtual machine. The multi-thread created may be a virtual thread and needs to be polling and scheduled by the python virtual machine, which greatly reduces the availability of Python multi-thread. Today, we have used classic producer and consumer issues to explain how to use multiple threads in Python.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 ( 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 ( 'Sumer' , Queue )
Print 'Starting threads ...'
Producer . Start ()
Consumer . Start ()
Producer . Join ()
Consumer . Join ()
Print 'All threads have terminated .'
If _ Name __ = '_ Main __' :
Main ()
you may feel different when running this code disconnection yourself! After understanding this, you can use Python cookielib and then use Python urllib to write a multi-thread download web page script. The author is: Old Wang @ Python tutorial Old Wang python, python tutorials and Python downloads related to pythn are provided. I hope you will like them