Introduction to python multi threaded applications
- 2020-04-02 09:47:12
- OfStack
Python easily supports multithreading. Can quickly create threads, mutex, semaphore and other elements, support thread read and write synchronization mutex. The fly in the ointment is that python runs on a python virtual machine, and the multiple threads created may be virtual threads that need to be polled and scheduled by the python virtual machine, which greatly reduces the availability of python multithreading. Today we use the classic producer and consumer question to illustrate the use of python's multi-threading 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('Consumer', queue)
print 'Starting threads ...'
producer.start()
consumer.start()
producer.join()
consumer.join()
print 'All threads have terminated.'
if __name__ == '__main__':
main()
You personally run this broken code, may have a different feeling! Understand that you can use python cookielib to write a multi-threaded script for downloading web pages in python urllib later