python可以方便地支持多線程。可以快速創(chuàng)建線程、互斥鎖、信號量等等元素,支持線程讀寫同步互斥。美中不足的是,python的運(yùn)行在python 虛擬機(jī)上,創(chuàng)建的多線程可能是虛擬的線程,需要由python虛擬機(jī)來輪詢調(diào)度,這大大降低了python多線程的可用性。我們經(jīng)今天用了經(jīng)典的生產(chǎn)者和消費(fèi)者的問題來說明下python的多線程的運(yùn)用 上代碼:
#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()
你親自運(yùn)行下這斷代碼,可能有不一樣的感覺!理解以后可以用python cookielib 再結(jié)果python urllib 寫一個(gè)多線程下載網(wǎng)頁的腳本應(yīng)該沒什么問題
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
