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 寫一個多線程下載網頁的腳本應該沒什么問題
新聞熱點
疑難解答