python可以方便地支援多線程。可以快速建立線程、互斥鎖、訊號量等等元素,支援線程讀寫同步互斥。美中不足的是,python的運行在python 虛擬機器上,建立的多線程可能是虛擬線程,需要由python虛擬機器來輪詢調度,這大大降低了python多線程的可用性。我們經今天用了經典的生產者和消費者的問題來說明下python的多線程的運用 上代碼:
複製代碼 代碼如下:#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()
你親自運行下這斷代碼,可能有不一樣的感覺!理解以後可以用python cookielib 再結果python urllib 寫一個多線程下載網頁的指令碼應該沒什麼問題