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