Python supports multiple threads. It allows you to quickly create threads, mutex locks, semaphores, and other elements. it supports thread read/write synchronization, mutex, and python can easily support multithreading. 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 the classic producer and consumer issues to illustrate the python multi-thread usage code:
The 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. fetch data = queue
Def run (self ):
For I in range (20 ):
Print self. getName (), 'adding', I, 'to queue'
Self. fetch data. 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. fetch data = queue
Def run (self ):
For I in range (20 ):
Print self. getName (), 'got a value: ', self. fetch data. 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 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.